【问题标题】:How to avoid requests.exceptions.ConnectionError for printing url text?如何避免 requests.exceptions.ConnectionError 打印 url 文本?
【发布时间】:2020-11-30 16:49:57
【问题描述】:

我无法打印 url 的文本。我做错了什么?

import requests

r = requests.get('https://www.autozone.com/ecomm/b2c/v1/browse/page/getProductFitVehicles?skuId=937722&productLineCode=NGK&partNumber=4469')

print(r.text)

追溯

requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(54, 'Connection reset by peer'))

【问题讨论】:

    标签: python url web-scraping text python-requests


    【解决方案1】:

    你需要设置一个用户代理,它甚至不必是连贯的

    import requests
    #Set headers
    headers = {'user-agent': 'my-app/0.0.1'}
    #Add , headers=headers at the end of line before closing the parentheses
    r = requests.get('https://www.autozone.com/ecomm/b2c/v1/browse/page/getProductFitVehicles?skuId=937722&productLineCode=NGK&partNumber=4469', headers=headers)
    
    print(r.text)
    
    

    【讨论】:

    • 您好,这仍然返回错误。 requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(54, 'Connection reset by peer')) >>>
    • 你用的是什么版本的python??
    • 等待您使用的是代理还是 vpn??
    【解决方案2】:

    r 不是变量而是对象。好像你想打印响应,试试这个:

    print(r.content)
    

    print(r.text)
    

    【讨论】:

    • 脚本最后一行是 print(r.text)
    • 我知道,我指出 .consent 的使用频率远高于 .text。但是,现在,如果您的连接被对等方重置,请尝试使用您的终端 ping 主机,看看它是来自您这边还是来自 url 本身的错误。尝试也从您的浏览器访问它。
    猜你喜欢
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 2021-05-24
    • 2011-11-28
    • 2021-06-30
    相关资源
    最近更新 更多