用于记录python爬虫学习的案例
利用python爬虫,基础爬取图片
代码如下:
import urllib.request
import re
header={
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
}
#构建报头
opener=urllib.request.build_opener()
opener.addheaders=header.items()
#安装为全局
urllib.request.install_opener(opener)
url="https://read.douban.com/provider/63750322/"
html=urllib.request.urlopen(url).read().decode("utf-8","ignore")
#构造正则表达式
pat='<img width="110px" height="165px" src="https://(.*?)"'
data=re.compile(pat,re.S).findall(html)
for i in range(0,len(data)):
localpath="E:/python_practice/image/image"+str(i+1)+".jpg"
this_url="https://%s"%data[i]
urllib.request.urlretrieve(this_url,filename=localpath)
这样以后就可以爬取图片,爬取图片展示如下: