您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

深入解析Python中的urllib2模块

2024/5/12 4:59:04发布23次查看
python 标准库中有很多实用的工具类,但是在具体使用时,标准库文档上对使用细节描述的并不清楚,比如 urllib2 这个 http 客户端库。这里总结了一些 urllib2 的使用细节。
proxy 的设置 timeout 设置 在 http request 中加入特定的 header redirect cookie 使用 http 的 put 和 delete 方法 得到 http 的返回码 debug logproxy 的设置
urllib2 默认会使用环境变量 http_proxy 来设置 http proxy。如果想在程序中明确控制 proxy 而不受环境变量的影响,可以使用下面的方式
import urllib2enable_proxy = trueproxy_handler = urllib2.proxyhandler({http : 'http://some-proxy.com:8080'})null_proxy_handler = urllib2.proxyhandler({})if enable_proxy:opener = urllib2.build_opener(proxy_handler)else:opener = urllib2.build_opener(null_proxy_handler)urllib2.install_opener(opener)
这里要注意的一个细节,使用 urllib2.install_opener() 会设置 urllib2 的全局 opener 。这样后面的使用会很方便,但不能做更细粒度的控制,比如想在程序中使用两个不同的 proxy 设置等。比较好的做法是不使用 install_opener 去更改全局的设置,而只是直接调用 opener 的 open 方法代替全局的 urlopen 方法。
timeout 设置
在老版 python 中,urllib2 的 api 并没有暴露 timeout 的设置,要设置 timeout 值,只能更改 socket 的全局 timeout 值。
import urllib2import socketsocket.setdefaulttimeout(10) # 10 秒钟后超时urllib2.socket.setdefaulttimeout(10) # 另一种方式
在 python 2.6 以后,超时可以通过 urllib2.urlopen() 的 timeout 参数直接设置。
import urllib2response = urllib2.urlopen('http://www.google.com', timeout=10)
在 http request 中加入特定的 header
要加入 header,需要使用 request 对象:
import urllib2request = urllib2.request(uri)request.add_header('user-agent', 'fake-client')response = urllib2.urlopen(request)
对有些 header 要特别留意,服务器会针对这些 header 做检查
user-agent : 有些服务器或 proxy 会通过该值来判断是否是浏览器发出的请求
content-type : 在使用 rest 接口时,服务器会检查该值,用来确定 http body 中的内容该怎样解析。常见的取值有:
application/xml : 在 xml rpc,如 restful/soap 调用时使用 application/json : 在 json rpc 调用时使用 application/x-www-form-urlencoded : 浏览器提交 web 表单时使用在使用服务器提供的 restful 或 soap 服务时, content-type 设置错误会导致服务器拒绝服务
redirect
urllib2 默认情况下会针对 http 3xx 返回码自动进行 redirect 动作,无需人工配置。要检测是否发生了 redirect 动作,只要检查一下 response 的 url 和 request 的 url 是否一致就可以了。
import urllib2response = urllib2.urlopen('http://www.google.cn')redirected = response.geturl() == 'http://www.google.cn'
如果不想自动 redirect,除了使用更低层次的 httplib 库之外,还可以自定义 httpredirecthandler 类。
import urllib2class redirecthandler(urllib2.httpredirecthandler):def http_error_301(self, req, fp, code, msg, headers):passdef http_error_302(self, req, fp, code, msg, headers):passopener = urllib2.build_opener(redirecthandler)opener.open('http://www.google.cn')
cookie
urllib2 对 cookie 的处理也是自动的。如果需要得到某个 cookie 项的值,可以这么做:
import urllib2import cookielibcookie = cookielib.cookiejar()opener = urllib2.build_opener(urllib2.httpcookieprocessor(cookie))response = opener.open('http://www.google.com')for item in cookie:if item.name == 'some_cookie_item_name':print item.value
使用 http 的 put 和 delete 方法
urllib2 只支持 http 的 get 和 post 方法,如果要使用 http put 和 delete ,只能使用比较低层的 httplib 库。虽然如此,我们还是能通过下面的方式,使 urllib2 能够发出 put 或 delete 的请求:
import urllib2request = urllib2.request(uri, data=data)request.get_method = lambda: 'put' # or 'delete'response = urllib2.urlopen(request)
得到 http 的返回码
对于 200 ok 来说,只要使用 urlopen 返回的 response 对象的 getcode() 方法就可以得到 http 的返回码。但对其它返回码来说,urlopen 会抛出异常。这时候,就要检查异常对象的 code 属性了:
import urllib2try:response = urllib2.urlopen('http://restrict.web.com')except urllib2.httperror, e:print e.codedebug log
使用 urllib2 时,可以通过下面的方法把 debug log 打开,这样收发包的内容就会在屏幕上打印出来,方便调试,有时可以省去抓包的工作
import urllib2httphandler = urllib2.httphandler(debuglevel=1)httpshandler = urllib2.httpshandler(debuglevel=1)opener = urllib2.build_opener(httphandler, httpshandler)urllib2.install_opener(opener)response = urllib2.urlopen('http://www.google.com')
ps: 借助urllib2抓取网站生成rss
看了看oschina的博客页面,发现可以使用python来抓取.记得前段时间看到有人使用python的rss模块pyrss2gen生成了rss.于是忍不住手痒自己试着实现了下,幸好还是成功了,下面代码共享给大家.
首先需要安装pyrss2gen模块和beautifulsoup模块,pip安装下就好了,我就不再赘述了.
下面贴出代码
# -*- coding: utf-8 -*-from bs4 import beautifulsoupimport urllib2import datetimeimport timeimport pyrss2genfrom email.utils import formatdateimport reimport sysimport osreload(sys)sys.setdefaultencoding('utf-8')class rssspider(): def __init__(self): self.myrss = pyrss2gen.rss2(title='oschina', link='http://my.oschina.net', description=str(datetime.date.today()), pubdate=datetime.datetime.now(), lastbuilddate = datetime.datetime.now(), items=[] ) self.xmlpath=r'/var/www/myrss/oschina.xml' self.baseurl=http://www.oschina.net/blog #if os.path.isfile(self.xmlpath): #os.remove(self.xmlpath) def useragent(self,url): i_headers = {user-agent: mozilla/5.0 (windows nt 6.1; wow64) \ applewebkit/537.36 (khtml, like gecko) chrome/36.0.1985.125 safari/537.36, \ referer: 'http://baidu.com/'} req = urllib2.request(url, headers=i_headers) html = urllib2.urlopen(req).read() return html def enterpage(self,url): pattern = re.compile(r'\d{4}\s\d{2}\s\d{2}\s\d{2}\s\d{2}') rsp=self.useragent(url) soup=beautifulsoup(rsp) timespan=soup.find('div',{'class':'blogstat'}) timespan=str(timespan).strip().replace('\n','').decode('utf-8') match=re.search(r'\d{4}\s\d{2}\s\d{2}\s\d{2}\s\d{2}',timespan) timestr=str(datetime.date.today()) if match: timestr=match.group() #print timestr ititle=soup.title.string div=soup.find('div',{'class':'blogcontent'}) rss=pyrss2gen.rssitem( title=ititle, link=url, description = str(div), pubdate = timestr ) return rss def getcontent(self): rsp=self.useragent(self.baseurl) soup=beautifulsoup(rsp) ul=soup.find('div',{'id':'recentblogs'}) for li in ul.findall('li'): div=li.find('div') if div is not none: alink=div.find('a') if alink is not none: link=alink.get('href') print link html=self.enterpage(link) self.myrss.items.append(html) def saverssfile(self,filename): finallxml=self.myrss.to_xml(encoding='utf-8') file=open(self.xmlpath,'w') file.writelines(finallxml) file.close()if __name__=='__main__': rssspider=rssspider() rssspider.getcontent() rssspider.saverssfile('oschina.xml')
可以看到,主要是使用beautifulsoup来抓取站点然后使用pyrss2gen来生成rss并保存为xml格式文件.
顺便共享下我生成的rss地址
http://104.224.129.109/myrss/oschina.xml
大家如果不想折腾的话直接使用feedly订阅就行了.
脚本我会每10分钟执行一次的.
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product