requests库(正则提取)爬取千图网
首先分析网页结构
打开千图网的网址搜索春节
打开网页源代码,发现跳转链接存在网页源代码里
接下来我们就利用正则表达式去提取
正则表达式最主要的就是找到你想要信息的标识符,例如上图,一页图片36 张,我们利用stats-point=“1121”>找到的也是36个,所以正则表达式就很好写了。代码如下:
baseurllist=re.findall('stats-point="1121"><a href="(.*?)" target="_blank" data-id',req.text)
print(baseurllist)
这样我们就可以得到一页里所有图片的跳转链接,以列表的形式返回,然后就可以去跳转链接里拿图片的大图了,首页展示的都是图片的缩略图,我们的目标是拿完整大图
随便打开一个跳转链接,分析跳转链接的网页结构
打开跳转页面的源代码
发现<meta property=“og:image” content="是图片链接的唯一标识符,所以:
photourl=re.findall('<meta property="og:image" content="(.*?)"',rsq.text)
photourl1='http:{}'.format(photourl[0])
print(photourl)
这样我们就可以提取到图片的下载链接了
最后进行下载就OK了
完整代码如下:
import re
import requests
def get_data(page):
a=1
for k in range(1,page+1):
url='https://www.58pic.com/tupian/qiche-0-0-{}.html'.format(k)
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'
}
req=requests.get(url,headers=headers)
print(req.text)
baseurllist=re.findall('stats-point="1121"><a href="(.*?)" target="_blank" data-id',req.text)
print(baseurllist)
for i in range(0,len(baseurllist)):
baseurl='http:{}'.format(baseurllist[i])
rsq=requests.get(baseurl)
photourl=re.findall('<meta property="og:image" content="(.*?)"',rsq.text)
photourl1='http:{}'.format(photourl[0])
photo=requests.get(photourl1,headers=headers)
print(photourl)
with open('E:\\PyCharm Community Edition 2019.1.2\\dasj\\requests库实践\\千图网\\{}.jpg'.format(a), 'wb') as f:
f.write(photo.content)
a+=1
print('==' * 10, '第{}页已经完毕'.format(k), '==' * 10)
if __name__ == '__main__':
page=int(input('请输入爬取页数:'))
get_data(page)
注:本文章仅供参考学习