没有合适的资源?快使用搜索试试~ 我知道了~
首页python爬取网页时response.status_code返回418,文件读取写入
python爬取网页时response.status_code返回418,文件读取写入
5星 · 超过95%的资源 4 下载量 72 浏览量
更新于2023-03-16
评论
收藏 52KB PDF 举报
问题: response.status_code为418 问题描述: 当我使用Python的requests爬取网页时response和soup都是None,检查后发现response.status_code为418 错误描述: 经过网上查询得知,418的意思是被网站的反爬程序返回的,网上解释为,418 I’m a teapot The HTTP 418 I’m a teapot client error response code indicates that the server refuses to brew coffee because it is a teapot. This
资源详情
资源评论
资源推荐
python爬取网页时爬取网页时response.status_code返回返回418,文件读,文件读
取写入取写入
问题:问题:
response.status_code为418
问题描述:问题描述:
当我使用Python的requests爬取网页时response和soup都是None,检查后发现response.status_code为418
错误描述:错误描述:
经过网上查询得知,418的意思是被网站的反爬程序返回的,网上解释为,418 I’m a teapot
The HTTP 418 I’m a teapot client error response code indicates that the server refuses to brew coffee because it is a teapot.
This error is a reference to Hyper Text Coffee Pot Control Protocol which was an April Fools’ joke in 1998.
翻译为:HTTP 418 I’m a teapot客户端错误响应代码表示服务器拒绝煮咖啡,因为它是一个茶壶。这个错误是对1998年愚人
节玩笑的超文本咖啡壶控制协议的引用。
解决办法:解决办法:
当时用了requests库,没有添加请求头等信息,可能被反爬程序识别了,再次请求添加了header的User-Agent信息就可以了。
代码:代码:
import requests
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/79.0.3945.88 Safari/537.36'}
res = requests.get(url,headers=headers)
以豆瓣图书为例:以豆瓣图书为例:
import requests
class DouBan:
def __init__(self, type):
'''
初始化方法,当创建一个类的对象的时候,该方法会被自动执行,不需要手动调用
'''
self.book_type = type
self.url = "https://book.douban.com/tag/"+self.book_type+"?start={}&type=T"
def get_urls(self):
'''该方法用来构造所有的url'''
# 列表生成式
return [self.url.format(20*i) for i in range(5)]
def parse_url(self, url):
'''发送请求并解析数据'''
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/79.0.3945.88 Safari/537.36'}
response = requests.get(url, headers=headers)
return response.content.decode()
def save_data(self, content, page_count):
'''保存数据'''
file_name = '豆瓣图书-{}-第{}页.html'.format(self.book_type, page_count)
with open('./DouBan/' + file_name, 'w', encoding='utf-8') as f:
f.write(content)
def run(self):
'''爬虫程序启动'''
# 1. 构造url地址
request_list = self.get_urls()
weixin_38626928
- 粉丝: 2
- 资源: 949
上传资源 快速赚钱
- 我的内容管理 收起
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
会员权益专享
最新资源
- c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf
- 建筑供配电系统相关课件.pptx
- 企业管理规章制度及管理模式.doc
- vb打开摄像头.doc
- 云计算-可信计算中认证协议改进方案.pdf
- [详细完整版]单片机编程4.ppt
- c语言常用算法.pdf
- c++经典程序代码大全.pdf
- 单片机数字时钟资料.doc
- 11项目管理前沿1.0.pptx
- 基于ssm的“魅力”繁峙宣传网站的设计与实现论文.doc
- 智慧交通综合解决方案.pptx
- 建筑防潮设计-PowerPointPresentati.pptx
- SPC统计过程控制程序.pptx
- SPC统计方法基础知识.pptx
- MW全能培训汽轮机调节保安系统PPT教学课件.pptx
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论10