6.21自我总结
一.爬取斗图网
1.摘要
使用xpath匹配规则查找对应信息文件
将请求伪装成浏览器
Referer 防跨域请求
2.爬取代码
import requests
url = 'http://www.doutula.com/'
'''
Referer: http://www.doutula.com/ Referer为防跨域请求,我看了下图片都是这个所有也可以不加上去,这个简单来说就是你只能通过这个网址来找到图片,如果他和url不同我们也把他加入再hearders里面,和下面保存一起
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36
'''
hearders = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',}
response = requests.get(url,headers=hearders)
'''
data-original="http://ww4.sinaimg.cn/bmiddle/9150e4e5gy1g48gluqdp6j203c03ct92.jpg"
'''
img_xpath = './/img/@data-original'
from lxml.html import etree
html = etree.HTML(response.text)
img_url = html.xpath(img_xpath)
import os
img_file_path = os.path.join(os.path.dirname(__file__),'img')
if not os.path.exists(img_file_path):
os.mkdir(img_file_path)
count = 1
for img in img_url:
img_path = os.path.join(img_file_path,f'第{count}张.jpg')
with open(img_path,'wb') as fw:
img_response = requests.get(img)
img_response = img_response.content
fw.write(img_response)
count +=1
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步