【问题标题】:Requests.get not working with certain URLsRequests.get 不适用于某些 URL
【发布时间】:2020-10-19 02:24:20
【问题描述】:

我正在尝试使用 Python 的请求库发出 Get 请求。我可以很好地运行快速入门示例,但是当我更改 URL 时,代码很长时间没有返回,最后返回了一些错误,这些错误引用了请求库代码中的深层代码。我一直在尝试用谷歌搜索,但这超出了我初学者的理解范围。传递给 requests.get() 的 URL 的语法是否有一些限制?以下是 URL 无效的代码:

import requests

URL = 'https://www.landsofamerica.com/United-States/lakefront-property/'
r = requests.get(URL)
print(r.text)

"""
NOTE: This code taken from https://requests.readthedocs.io/en/master/user/quickstart/#make-a-request

The example code in the docs *does* execute correctly with this example URL:
URL = 'https://api.github.com/events'

"""

返回的错误很长,我不知道如何找到“最相关的部分”来寻求帮助,所以我认为我不应该把这些都粘贴在这里?谢谢。

【问题讨论】:

    标签: get python-requests


    【解决方案1】:

    该网站可能正在阻止抓取请求。

    使用 headers 集合来模拟浏览器。

    import requests
    
    URL = 'https://www.landsofamerica.com/United-States/lakefront-property'
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    
    r = requests.get(URL, headers=headers)
    print(r.text)
    

    补充资料:How to use Python requests to fake a browser visit?

    【讨论】:

      猜你喜欢
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 2013-08-12
      • 1970-01-01
      • 2018-09-12
      • 2012-10-28
      相关资源
      最近更新 更多