import requests
import re
import os
'''爬取糗事百科所有图片(利用re表达式)'''
# 如果目录不存在,则创建目录
if not os.path.exists('./pics'):
os.makedirs('./pics')
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
}
# 循环访问页数
for i in range(1,11):
url="https://www.qiushibaike.com/imgrank/page/%d/"%(i)
# 得到页面数据
html_data=requests.get(url=url,headers=headers)
html_text=html_data.text
# 利用re表达式,得到图片网址
ex='<img src="//pic.qiushibaike.com/system/pictures/(.*?)" alt='
list_jpg=re.findall(ex,html_text,re.S)
for jpg_url in list_jpg:
# 生成图片名字
jpg_name=jpg_url.split('/')[-1]
# 合成图片网址
jpg_url="https://pic.qiushibaike.com/system/pictures/"+jpg_url
# 得到图片数据
# text字符串 content 二进制数据 json对象
jpg_response=requests.get(url=jpg_url,headers=headers).content
# 二进制方式写入数据
with open('./pics/'+jpg_name,'wb') as fp:
fp.write(jpg_response)
print(jpg_name,"success")
总结:注意content为二进制数据,写入图片用