首页 编程教程正文

使用Python3编写抓取网页和只抓网页图片的脚本

piaodoo 编程教程 2020-02-02 12:30:37 936 0 python教程

这篇文章主要介绍了使用Python3编写抓取网页和只抓网页图片的脚本,使用到了urllib模块,需要的朋友可以参考下

最基本的抓取网页内容的代码实现:

#!/usr/bin/env python 
 
from urllib import urlretrieve 
 
def firstNonBlank(lines): 
  for eachLine in lines: 
    if not eachLine.strip(): 
      continue 
    else: 
      return eachLine 
 
def firstLast(webpage): 
  f = open(webpage) 
  lines = f.readlines() 
  f.close() 
  print firstNonBlank(lines), 
  lines.reverse() 
  print firstNonBlank(lines), 
 
def download(url='http://www',process=firstLast): 
  try: 
    retval = urlretrieve(url)[0] 
  except IOError: 
    retval = None 
  if retval: 
    process(retval) 
 
if __name__ == '__main__': 
  download() 

利用urllib模块,来实现一个网页中针对图片的抓取功能:

import urllib.request 
import socket 
import re 
import sys 
import os 
targetDir = r"C:\Users\elqstux\Desktop\pic" 
def destFile(path): 
  if not os.path.isdir(targetDir): 
    os.mkdir(targetDir) 
  pos = path.rindex('/') 
  t = os.path.join(targetDir, path[pos+1:]) 
  return t 
 
if __name__ == "__main__": 
  hostname = "http://www.douban.com" 
  req = urllib.request.Request(hostname) 
  webpage = urllib.request.urlopen(req) 
  contentBytes = webpage.read() 
  for link, t in set(re.findall(r'(http:[^\s]*?(jpg|png|gif))', str(contentBytes))): 
    print(link) 
    urllib.request.urlretrieve(link, destFile(link)) 

       

import urllib.request 
import socket 
import re 
import sys 
import os 
targetDir = r"H:\pic" 
def destFile(path): 
  if not os.path.isdir(targetDir): 
    os.mkdir(targetDir) 
  pos = path.rindex('/') 
  t = os.path.join(targetDir, path[pos+1:]) #会以/作为分隔 
  return t 
 
if __name__ == "__main__": 
  hostname = "http://www.douban.com/" 
  req = urllib.request.Request(hostname) 
  webpage = urllib.request.urlopen(req) 
  contentBytes = webpage.read() 
  match = re.findall(r'(http:[^\s]*?(jpg|png|gif))', str(contentBytes) )#r'(http:[^\s]*?(jpg|png|gif))'中包含两层圆括号,故有两个分组, 
                             #上面会返回列表,括号中匹配的内容才会出现在列表中 
  for picname, picType in match: 
    print(picname) 
    print(picType) 
    
 
''''' 
输出: 
http://img3.douban.com/pics/blank.gif 
gif 
http://img3.douban.com/icon/g111328-1.jpg 
jpg 
http://img3.douban.com/pics/blank.gif 
gif 
http://img3.douban.com/icon/g197523-19.jpg 
jpg 
http://img3.douban.com/pics/blank.gif 
gif 
... 
''' 

版权声明:

本站所有资源均为站长或网友整理自互联网或站长购买自互联网,站长无法分辨资源版权出自何处,所以不承担任何版权以及其他问题带来的法律责任,如有侵权或者其他问题请联系站长删除!站长QQ754403226 谢谢。

有关影视版权:本站只供百度云网盘资源,版权均属于影片公司所有,请在下载后24小时删除,切勿用于商业用途。本站所有资源信息均从互联网搜索而来,本站不对显示的内容承担责任,如您认为本站页面信息侵犯了您的权益,请附上版权证明邮件告知【754403226@qq.com】,在收到邮件后72小时内删除。本文链接:http://www.piaodoo.com/2061.html

评论

搜索