python爬虫系列(二):标准库的使用(A)
来源:互联网 发布:淘宝买家微信付款骗局 编辑:程序博客网 时间:2024/05/29 16:33
(一)Py2和Py3中的基本库使用的区分
Urllib库是python中的一个功能强大的,用于操作URL。python2和python3中用法基本相同,但是。python2中分为urllib和urllib2库。下面列出常见的变化有: 1.python2.x使用import urllib2-->python3.x使用import urllib.request, urllib.error2.python2.x使用import urllib -->python3.x使用import urllib.request, urllib.error,urllib.parse3.python2.x使用import urlparse-->python3.x使用import urllib.parse4.python2.x使用import urllib2.urlopen-->python3.x使用import urllib.request.urlopen5.python2.x使用import urllib2.quote-->python3.x使用import urllib.request.quote6.python2.x使用cookielib.CookieJar-->python3.x使用 http.CookieJar7.python2.x使用import urllib2.Request-->python3.x使用import urllib.request.Request大概也就这几种常用到的模块。希望能认真的区分,这能让你轻松面对两个版本的python。
(二)通过实际代码来介绍各种模块的应用。
Ps:本人一直使用py3.5版本,所以如版本不同,请自行按照一中介绍的进行切换。 小试牛刀:import urllib.requestimport urllib.parseimport http.cookiejarurl = "http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmint=yes&loginhash=L768q"postdata = urllib.parse.urlencode({'usrname':'用户名','password':'密码'}).encode('utf-8')req = urllib.request.Request(url,postdata)req.add_header('User-Agent','Mozilla/5.0 (windows NT 6.1; WOW64) AppleWebkit/537.36')cjar = http.cookiejar.CookieJar()opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cjar))urllib.request.install_opener(opener)file = opener.open(req)print (file.read().decode('gbk'))
代码难点解析:这段代码虽然小,但却涵盖了常用到的爬虫模块了。通过urllib.request发送请求,把要登陆的用户和密码在通过urlencode的解析后构建post请求对象。
在这里要强调–> 我们访问的每一个互联网页面都是通过Http协议进行。而http 协议是一个无状态协议。所谓的无状态协议就是无法维持会话之间的状态。为了保持会话的畅通,cookie和session应运而生。
所以,这里的代码进行了cookie的对象的设置。即cjar = http.cookiejar.CookieJar()。然后自己创建了一个opener对象,携带cookier对象。
注:urlencode的作用:接受参数形式为:[(key1, value1), (key2, value2),…] 和 {‘key1’: ‘value1’, ‘key2’: ‘value2’,…}
返回的是形如key2=value2&key1=value1字符串。
urllib.urlencode({‘name’: u’老王’.encode(‘utf8’), ‘sex’: u’男’.encode(‘utf8’)})
‘name=%E8%80%81%E7%8E%8B&sex=%E7%94%B7’
@关于cookie和session的使用,在接下来的系列中会详细介绍。如果有什么问题可以一起探讨一下。
阅读全文
0 0
- python爬虫系列(二):标准库的使用(A)
- Python爬虫(二)之使用标准库爬取糗事百科段子
- python爬虫系列(七):XPath的使用
- python爬虫系列二
- python 爬虫(二)
- python爬虫(二)
- python爬虫(二)
- Python 爬虫(二)
- Python从零开始写爬虫(二)BeautifulSoup库使用
- python爬虫系列(三):第三方库requests 的使用
- 爬虫入门系列(二):优雅的HTTP库requests
- 用Python写网络爬虫系列(二)------数据获取
- python爬虫系列之爬取百度文库(二)
- python爬虫系列(一):爬虫简介
- Python爬虫系列(二)Quotes to Scrape(谚语网站的爬取实战)
- Python爬虫二(Urllib库的基本使用和高级用法)
- 爬虫系列之二 urllib2库的使用上
- 我的Python爬虫(二):买肾六
- 全方位认识SQLite(一)
- SAS导入文件和数据集用法举例
- 找零钱问题
- 冒泡排序(python实现)
- Redis的AOF功能
- python爬虫系列(二):标准库的使用(A)
- 免备案在国内服务器搭建网站或在自己电脑搭建网站(本地连接没有链接到DHCP)
- KMP算次数
- 全方位认识SQLite(二)
- rabbimq 的使用和管理
- java多线程有返回值
- JAVA微信公众号开发——上传图片,新增永久素材,群发
- java萌新的成长之路--linux初识
- activeMQ的原理及使用