【问题标题】:unable to requests.get() a website, 'Remote end closed connection without response'无法请求.get()网站,“远程结束关闭连接而无响应”
【发布时间】:2018-11-08 21:50:15
【问题描述】:

当我尝试向该网站发送请求时:

import requests
requests.get('https://www.ldoceonline.com/')

返回异常

requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

奇怪的是,如果您通过普通方法(通过浏览器)访问该网站,它们功能齐全并且响应非常好。只有当您尝试通过网络抓取技术检索信息时,您才会遇到此响应。

知道如何成功抓取它吗?

【问题讨论】:

    标签: python web-scraping


    【解决方案1】:

    尝试使用标头来获得所需的响应。

    import requests
    
    res = requests.get('https://www.ldoceonline.com/',headers={"User-Agent":"Mozilla/5.0"})
    print(res.status_code)
    

    输出:

    200
    

    【讨论】:

    • 您能否解释一下为什么标头可以解决问题?
    • this link 一个明确的目标。
    【解决方案2】:

    如果您检查请求模块的code,您会发现发出请求时使用的default headers 的值。上面提到的User-Agent 标头也在那里。

    如果将 User-Agent 标头设置为“python-requests/2.21.0”,似乎一堆网络资源(无论有意还是无意)无法正确处理请求。

    所以实际的解决方案是使用自定义 User-Agent 标头。提供了不同浏览器的用户代理字符串here

    import requests
    
    url = 'https://www.ldoceonline.com/'
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36"}
    
    r = requests.get(url,headers=headers)
    r.raise_for_status()
    

    【讨论】:

      猜你喜欢
      • 2021-08-20
      • 2021-10-21
      • 2023-03-03
      • 1970-01-01
      • 2017-03-12
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      相关资源
      最近更新 更多