python2和python3中urllib的用版本区别及用法 爬虫基础

来源:互联网 发布:js闭包 编辑:程序博客网 时间:2024/06/04 23:36

首先在python2中urllib和urllib2的区别:

1.urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL。这意味着,你不可以通过urllib模块伪装你的User Agent字符串等(伪装浏览器)。
2.urllib提供urlencode方法用来GET查询字符串的产生,而urllib2没有。这是为何urllib常和urllib2一起使用的原因。
3.urllib2模块比较优势的地方是urlliburllib2.urlopen可以接受Request对象作为参数,从而可以控制HTTP Request的header部。
4.但是urllib.urlretrieve函数以及urllib.quote等一系列quote和unquote功能没有被加入urllib2中,因此有时也需要urllib的辅助。


先看看python2中urllib2的使用方法

#coding:utf-8# python2.7版本import urllib2# 设置浏览器请求头ua_headers={    "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0"}#建立请求内容request=urllib2.Request("http://baidu.com/",headers=ua_headers)#获取响应response=urllib2.urlopen(request)#页面内容html=response.read()print htmlprint response.getcode() #返回响应码print response.geturl() #返回实际urlprint response.info() #返回服务器响应的报头

在看看python3中urllib2的用法

from urllib import requesturl = r'https://www.baidu.com/'headers = {    'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '                  r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',    'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',    'Connection': 'keep-alive'}req = request.Request(url, headers=headers)html = request.urlopen(req).read()# 处理编码html = html.decode('utf-8')print(html)


原创粉丝点击