爬虫过程报错:http.client.RemoteDisconnected: Remote end closed connection without response

import urllib
from urllib import request
page = 1
url = 'http://www.qiushibaike.com/hot/page/'+str(page)
#url = 'http://www.baidu.com'
try:
	req = request.Request(url)
	response = request.urlopen(req)
	print(response.read())
except urllib.request.URLError as e:
	if hasattr(e,'code'):
		print(e.code())
	if hasattr(e,'reason'):
		print(e,reason())

利用 urllib 发起的请求,UA 默认是 Python-urllib/3.5 而在 chrome 中访问 UA 则是 User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36,因为服务器根据 UA 来判断拒绝了 python 爬虫。

 

import urllib
from urllib import request
page = 1
url = 'http://www.qiushibaike.com/hot/page/'+str(page)
#url = 'http://www.baidu.com'
def getHTML(url):
	headers = {'User-Agent': 'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
	req = request.Request(url, headers=headers)
	return request.urlopen(req)

try:
	response = getHTML(url)
	print(response.read())
except urllib.request.URLError as e:
	if hasattr(e,'code'):
		print(e.code())
	if hasattr(e,'reason'):
		print(e,reason())
	


把 python 伪装成 chrome 去获取糗百的网页,可以顺利的得到数据。

【本文由“仲肥”发布,2018年7月31日】

 

 

 

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值