Python爬虫学习--urllib的基本使用笔记
2017-08-20 23:52
666 查看
一.访问一个 Page的方法:
1>urlopen方法:
req = urllib.request.Request("http://www.zte.com.1s") data = urllib.request.urlopen(req,timeout=1).read() #超时1s
生成Request对象,再通过urlopen的方法访问页面(包括DNS),再通过read方式将html内容读出。
2>build_opener对象的 open方法:
viewer = urllib.request.build_opener() viewer.addheaders = [header] data = viewer.open("http://www.zte.com.cn").read()
创建build_opener对象,调用opener对象的open方法打开url.opener对象结合其他特性一起使用更灵活 。
二.模仿正式浏览器访问:
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36')
Request对象的add_header方法,填入真实浏览器访问页面时携带的信息。
三.使用代理访问:
def install_proxy(proxy_addr): proxy = request.ProxyHandler({'http':proxy_addr}) opener = request.build_opener(proxy,request.ProxyHandler) request.install_opener(opener) install_proxy('111.155.116.239:8123')
创建ProxyHandler 代理对象,创建build_opener对象并作为入参传入,最后使用install_opener方法设置为全局
四.打印Debug信息:
http_dbg = request.HTTPHandler(debuglevel=1) opener = request.build_opener(.....http_dbg ) request.install_opener(opener)
创建HTTPHandler对象,并设置打印级别,在创建opener对象时,作为入参传入
五.cookie的使用:
import http.cookiejar ....... cjar = http.cookiejar.CookieJar() opener = request.build_opener(request.HTTPCookieProcessor(cjar)) request.install_opener(opener)
在创建Opener对象时作为传入CookieJar对象。
六.创建并访问中文URL(quote)
keys = ["邰晓梅","MFQ"] url_temp = 'http://www.baidu.com/s?wd=%s' for key in keys: key_encode = urllib.request.quote(key) #quote进行编码解决URL中不支持的ASCII req = urllib.request.Request(url_temp % key_encode )
七.下载、保存URL中的图片一条龙:
request.urlretrieve("http://%s" % url,"%s/%s" %(ret_path,pic_name))
将从page中趴到图片ur,下载并保存到pic_name路径中
八.异常处理:
# # HTTPError只包括HTTP应用层的错误捕获 # except urllib.error.HTTPError as e: # print("code:%s reason:%s" %(e.code,e.reason) ) # # URLError包括了HTTPError和底层传输错误 # except urllib.error.URLError as e: # print("reason:%s" % (e.reason) )
整合这两个 except 可以只使用 URLError,然后用hassattr判断e没有没有code属性来决定是否打印:
except urllib.error.URLError as e: if hasattr(e,'code'): print("code:%s reason:%s" % (e.code, e.reason)) else : print("reason:%s" % e.reason)
相关文章推荐
- Python爬虫框架Scrapy 学习笔记 5 ------- 使用pipelines过滤敏感词
- 学习爬虫基础3-urllib2库的基本使用
- Python爬虫入门一之Urllib库的基本使用
- Python3爬虫学习笔记(1.urllib库详解)
- Python爬虫urllib笔记(四)之使用BeautifulSoup爬取百度贴吧
- Python3学习笔记(urllib模块的使用)转http://www.cnblogs.com/Lands-ljk/p/5447127.html
- python爬虫学习——urllib、urllib2库的使用
- Python3学习笔记 urllib模块的使用
- Python3.x学习笔记[2.5]灵活使用urllib与re
- [Python] - 爬虫之Urllib库的基本使用
- python2.7爬虫学习笔记(一)---Urllib库的使用
- Python爬虫入门之Urllib库的基本使用
- python多线程爬虫学习--urllib的使用
- Python爬虫入门之Urllib库的基本使用 (三)
- python爬虫:使用Mongodb数据库存储数据学习笔记
- 03—小白学Python爬虫之urllib的基本和进阶使用及Get、Post示例
- python爬虫学习笔记——使用requests库编写爬虫(1)
- Python3爬虫进阶urllib模块的使用笔记
- Python学习笔记-模块介绍(一)-模块概念和基本使用