【问题标题】:Python requests hangs whereas CURL doesn't (same request)Python 请求挂起,而 CURL 没有(相同的请求)
【发布时间】:2020-06-02 17:03:23
【问题描述】:

在尝试使用访问特定站点的请求读取响应时,我遇到了永久挂起,这很可能是由于某种阻塞。我不确定的是,成功接收响应的 CURL 与我从未收到任何响应的 Python 获取请求有何不同。

注意:curl 命令预计会返回错误,因为我没有发送所需的信息,例如 cookie 卷曲:

curl 'https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'

成功得到响应

Python:

import requests
r = requests.get('https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'})

永远挂在读

【问题讨论】:

  • 我也遇到了类似的错误。你能解决这个问题吗?

标签: http curl python-requests


【解决方案1】:

它适用于 python 3。

import requests
r = requests.get('https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'})
print(r.headers)

回复:

{'Cache-Control': 'max-age=86400, public', 'Content-Encoding': 'gzip', 'Content-Language': 'en-US', 'Content-Type': 'text/html;charset=utf-8', 'Server': 'Apache-Coyote/1.1', 'Vary': 'Accept-Encoding', 'X-Frame-Options': 'SAMEORIGIN', 'Content-Length': '8009', 'Date': 'Wed, 19 Feb 2020 06:04:55 GMT', 'Connection': 'keep-alive'}

【讨论】:

  • 我发现是ip比较的
【解决方案2】:

提出请求的方式可能存在细微差别。例如 Python 请求会自动添加一些标头:

'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'

(你可以通过执行看到它们:r.request.headers

Curl 会添加:Accept: */*,但不会添加 gzip,除非您要求。但是有问题的网站似乎支持 gzip,所以问题一定出在其他地方。

建议:在您的请求中添加超时,并捕获可能的异常,即:

try:
    r = requests...

except requests.exceptions.RequestException as e:
    print (e)

【讨论】:

  • 我尝试模拟确切的 CURL 请求标头无济于事。这是一个读取超时,当我给出一个超时参数时它会提供一个异常,所以不要认为我会从中得到任何有用的信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-12
相关资源
最近更新 更多