python爬取网页时返回http状态码HTTP Error 418

问题:urllib.error.HTTPError: HTTP Error 418:

问题描述:当我使用Python的request爬取网页时返回了http状态码为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年愚人节玩笑的超文本咖啡壶控制协议的引用。

解决办法:当时我用的是urllib的request,我感觉这个库应该有点久了,所以换了requests这个库,然后再次请求,并添加了header的信息就可以了,如果不加程序放回的是空,没有结果,运行不会错

使用request:

from urllib import request

r = request.urlopen(url)

html = r.read().decode("utf-8")

print(html)

使用requests并添加headers信息后:

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'}

r = requests.get(url,headers=headers)

html = r.text

print(html)

 
posted @ 2020-01-06 18:37  star====  阅读(24528)  评论(0编辑  收藏  举报