且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

设置用户代理User Agent访问网页(Python2.7)

更新时间:2022-09-28 17:38:34

1. 概念

User Agent用户代理,是一个标志,供服务端识别客户端的操作系统和浏览器情况。


比如,如果想判断访问网站的浏览器是否是微信浏览器,就可以判断用户代理,来实现网页仅能从微信自带浏览器访问。


另外,如果使用urllib2默认的代理字符串,可能会被某些网站屏蔽(不想被通过代码访问)。


2. 在python中设置代理

代码如下:

#!/usr/bin/python2.7
# coding=UTF-8
import urllib2

#变量区域
url="http://www.baidu.com/"#待下载的网址

#方法区域
def downloadWebsite(url,retry_time=5,user_agent="temp"):
    print("start to download:"+url+",the retry time is:"+str(retry_time))
    header={"User-Agent:":user_agent}
    request=urllib2.Request(url,headers=header)
    try:
        result=urllib2.urlopen(url).read()
    except urllib2.URLError as ex:
        if retry_time==1:
            return "download error,the reason is:"+ex.reason+",error code"+str(ex.code)
        else:
            return downloadWebsite(url,retry_time-1)
    return result

result=downloadWebsite(url)
print(result)

3. 更多设置

下面是一个通过Firefox浏览器查看的请求头情况,可见Linux和Firefox字样。根据上面的代码header={"User-Agent:":user_agent} request=urllib2.Request(url,headers=header),我们应该可以修改其他请求头的信息。

设置用户代理User Agent访问网页(Python2.7)