简体   繁体   English

在urllib2.urlopen上更改用户代理

[英]Changing user agent on urllib2.urlopen

如何使用urllib2.urlopen上默认用户代理以外的用户代理下载网页?

I answered a similar question a couple weeks ago. 几周前我回答类似的问题

There is example code in that question, but basically you can do something like this: (Note the capitalization of User-Agent as of RFC 2616 , section 14.43.) 该问题中有示例代码,但基本上您可以执行以下操作:(注意自RFC 2616起的User-Agent的大小写,第14.43节。)

opener = urllib2.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
response = opener.open('http://www.stackoverflow.com')
headers = { 'User-Agent' : 'Mozilla/5.0' }
req = urllib2.Request('www.example.com', None, headers)
html = urllib2.urlopen(req).read()

Or, a bit shorter: 或者,更短一些:

req = urllib2.Request('www.example.com', headers={ 'User-Agent': 'Mozilla/5.0' })
html = urllib2.urlopen(req).read()

Setting the User-Agent from everyone's favorite Dive Into Python . 从每个人最喜欢的Dive Into Python中 设置User-Agent

The short story: You can use Request.add_header to do this. 短篇小说:您可以使用Request.add_header来执行此操作。

You can also pass the headers as a dictionary when creating the Request itself, as the docs note : 您还可以在创建请求本身时将标题作为字典传递, 如文档所示

headers should be a dictionary, and will be treated as if add_header() was called with each key and value as arguments. 标题应该是一个字典,并且将被视为调用add_header()时每个键和值作为参数。 This is often used to “spoof” the User-Agent header, which is used by a browser to identify itself – some HTTP servers only allow requests coming from common browsers as opposed to scripts. 这通常用于“欺骗” User-Agent标头,浏览器使用该标头来标识自身 - 某些HTTP服务器仅允许来自常见浏览器而非脚本的请求。 For example, Mozilla Firefox may identify itself as "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11" , while urllib2 's default user agent string is "Python-urllib/2.6" (on Python 2.6). 例如,Mozilla Firefox可能将自己标识为"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11" ,而urllib2的默认用户代理字符串为"Python-urllib/2.6" (在Python上) 2.6)。

For python 3, urllib is split into 3 modules... 对于python 3,urllib分为3个模块......

import urllib.request
req = urllib.request.Request(url="http://localhost/", headers={'User-Agent':' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0'})
handler = urllib.request.urlopen(req)

All these should work in theory, but (with Python 2.7.2 on Windows at least) any time you send a custom User-agent header, urllib2 doesn't send that header. 所有这些都应该在理论上起作用,但是(至少在Windows上使用Python 2.7.2)每次发送自定义User-agent标头时,urllib2都不会发送该标头。 If you don't try to send a User-agent header, it sends the default Python / urllib2 如果您不尝试发送User-agent标头,它将发送默认的Python / urllib2

None of these methods seem to work for adding User-agent but they work for other headers: 这些方法似乎都不适用于添加User-agent,但它们适用于其他标头:

opener = urllib2.build_opener(proxy)
opener.addheaders = {'User-agent':'Custom user agent'}
urllib2.install_opener(opener)

request = urllib2.Request(url, headers={'User-agent':'Custom user agent'})

request.headers['User-agent'] = 'Custom user agent'

request.add_header('User-agent', 'Custom user agent')

For urllib you can use: 对于urllib您可以使用:

from urllib import FancyURLopener

class MyOpener(FancyURLopener, object):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'

myopener = MyOpener()
myopener.retrieve('https://www.google.com/search?q=test', 'useragent.html')

Another solution in urllib2 and Python 2.7: urllib2和Python 2.7中的另一个解决方案:

req = urllib2.Request('http://www.example.com/')
req.add_unredirected_header('User-Agent', 'Custom User-Agent')
urllib2.urlopen(req)

Try this : 试试这个 :

html_source_code = requests.get("http://www.example.com/",
                   headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36',
                            'Upgrade-Insecure-Requests': '1',
                            'x-runtime': '148ms'}, 
                   allow_redirects=True).content

there are two properties of urllib.URLopener() namely: urllib.URLopener()有两个属性,即:
addheaders = [('User-Agent', 'Python-urllib/1.17'), ('Accept', '*/*')] and addheaders = [('User-Agent', 'Python-urllib/1.17'), ('Accept', '*/*')]
version = 'Python-urllib/1.17' . version = 'Python-urllib/1.17'
To fool the website you need to changes both of these values to an accepted User-Agent. 要欺骗网站,您需要将这两个值更改为已接受的用户代理。 for eg 例如
Chrome browser : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36' Chrome浏览器: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36'
Google bot : 'Googlebot/2.1' 谷歌机器人: 'Googlebot/2.1'
like this 像这样

import urllib
page_extractor=urllib.URLopener()  
page_extractor.addheaders = [('User-Agent', 'Googlebot/2.1'), ('Accept', '*/*')]  
page_extractor.version = 'Googlebot/2.1'
page_extractor.retrieve(<url>, <file_path>)

changing just one property does not work because the website marks it as a suspicious request. 仅更改一个属性不起作用,因为该网站将其标记为可疑请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM