gpt4 book ai didi

python - 如何在 Python 2.7 中重新创建 urllib.requests?

转载 作者:太空宇宙 更新时间:2023-11-03 15:35:16 25 4
gpt4 key购买 nike

我正在抓取一些网页并解析其中的一些数据,但其中一个网站似乎阻止了我的请求。使用 Python 3 和 urllib.requests 的代码版本工作正常。我的问题是我需要使用Python 2.7,并且我无法使用 urllib2 获得响应

这些请求不应该是相同的吗?

Python 3 版本:

def fetch_title(url):
req = urllib.request.Request(
url,
data=None,
headers={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
}
)
html = urllib.request.urlopen(req).read().encode('unicode-escape').decode('ascii')

return html

Python 2.7 版本:

import urllib2

opener = urllib2.build_opener()
opener.addheaders = [(
'User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
)]
response = opener.open('http://website.com')

print response.read()

最佳答案

以下代码应该可以工作,基本上使用 python 2.7,您可以使用所需的 header 创建一个字典,并以一种可以使用 urllib2.Request 与 urllib2.urlopen 正常工作的方式格式化您的请求。

import urllib2

def fetch_title(url):
my_headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36"
}
return urllib2.urlopen(urllib2.Request(url, headers=my_headers)).read()

关于python - 如何在 Python 2.7 中重新创建 urllib.requests?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42568143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com