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

标签 python python-2.7 python-3.x python-requests urllib2

我正在抓取一些网页并解析其中的一些数据,但其中一个网站似乎阻止了我的请求。使用 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/

相关文章:

python-3.x - Selenium 使用 2captcha Python 提交 recaptcha

python - 用于列出 Jupyter 笔记本中使用的包版本的包

python - 如何将二进制类列转换为 numpy 数组

python - 如何读取缺少值和 'delim_whitespace=True'的csv文件?

python - 赋值时KeyError

python-3.x - 无法在 Airflow Python 3 中发布 Pubsub 消息

python - Python中一组列表的所有可能排列

python - 如何在 Sublime Text 插件中的特定行插入字符串?

Python:点击一个按钮

python - python 中是否有 chgrp -R 的等效项?