栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

成功解决:python爬虫http.client.RemoteDisconnected: Remote end closed connection without response

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

成功解决:python爬虫http.client.RemoteDisconnected: Remote end closed connection without response

参考:Python 爬虫:http.client.RemoteDisconnected: Remote end closed connection without response 问题解决
使用python爬虫中的urllib 或者 requests 库获取数据时
出现报错:

http.client.RemoteDisconnected: Remote end closed connection without response

原因:
大多数网站都会对用户请求中的 User-Agent 进行检测,如果没有在请求头中设置 User-Agent,那么就会抛出异常
改进方法:在headers中添加:User-Agent

import urllib.request
# 要访问的地址
headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36",
    try:
        postdata1 = urllib.parse.urlencode(data1).encode("UTF8")
        req_data1 = urllib.request.Request(login_url1, data=postdata1,headers=headers)
        response1 = urllib.request.urlopen(req_data1).read().decode("utf-8", "ignore")
        print(response1)
    except requests.ConnectionError as e:
        print('Error:', e.args)

requests中设置User-Agent如下:

import requests
headers = {
    'User-Agent': "Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1"
}
resp = requests.get(url, headers=headers)
print(resp.text)

暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1015238.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号