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

How can I recreate a urllib.requests in Python 2.7?

我正在抓取一些网页并解析其中的一些数据,但其中一个网站似乎阻止了我的请求。使用 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,你可以用你想要的 headers 创建一个字典,并以一种可以与 urllib2.urlopen 一起正常工作的方式格式化你的请求使用 urllib2.Request.

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()