python爬虫-urllib库学习

来源:互联网 发布:中森茗苑网易房产数据 编辑:程序博客网 时间:2024/06/13 04:54

知道了爬虫的爬取数据的基本原理后,其实我们不需要知道它的底层是怎么实现的,我们可以借助python自带的一个urllib库,request模块可以模拟一个浏览器访问,这时只需要关注 请求的url是什么,请求的数据是什么,以及headers 就可以了,另外error异常处理模块方便我们遇到异常时进行处理,urllib的数据解析工具parse也非常的强大。(有比urllib更好的库 就是requests,不过现在还是先学习这个 )

urlopen
1.get类型的:

response = urllib.request.urlopen('http://www.baidu.com')print(response.read().decode('utf-8'))

2.post类型的(需要传送一个data,需要是bytes类型,所以需要转化):

data = bytes(urllib.parse.urlencode({'world':'hello'}),encoding='utf-8')response = urllib.request.urlopen('http://www.baidu.com',data=data)

3.timeout(相应超时返回异常,捕获异常)

response
1.响应类型

typeresponse

2.状态码,响应头(判断响应是否成功的标志)

response.statusresponse.getheaders()response.getheader('Server')

3.read(获取响应体的内容,其实是bytes字节流的格式,还需要解码)

response.read().decode('utf-8')

Request(可以发送request对象,传送复杂的请求比如headers)
1.简单的 将url绑定未request对象:

request = urllib.request.Request('http://python.org')response = urllivb.request.urlopen(request)print(resonse.read().decode('utf-8'))

2.复杂的post请求(http://httpbin.org 这个网站适合各种测试)

from urllib import request, parseurl = 'http://httpbin.org/post'headers = {    'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',    'Host': 'httpbin.org'}dict = {    'name': 'Germey'}data = bytes(parse.urlencode(dict), encoding='utf8')req = request.Request(url=url, data=data, headers=headers, method='POST')response = request.urlopen(req)print(response.read().decode('utf-8'))

安装和使用ipython(anaconda已经集成了)
这里写图片描述

这里写图片描述

上面的headers是直接以参数添加的Request对象中去。还可以使用add_header方法加入(for循环添加多个)。

from urllib import request, parseurl = 'http://httpbin.org/post'dict = {    'name': 'Germey'}data = bytes(parse.urlencode(dict), encoding='utf8')req = request.Request(url=url, data=data, method='POST')req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')response = request.urlopen(req)print(response.read().decode('utf-8'))

前面的是基本的构造request,可以完成大部分网页的爬取。

Handler相当于辅助的工具,帮助处理额外的操作
比如代理设置伪装自己的ip,切换不同的ip这样才不会被检测出而被封掉ip,下面有http/https 代理,利用bulid-opener这样的一个方法将hander传过来,构建一个opener,再利用opener的open方法(和urllib中的urlopen基本是一样的。)下面的代码,运行时候当然不成功,因为需要有实际的代理账号或者软件之类的。

import urllib.requestproxy_handler = urllib.request.ProxyHandler({    'http': 'http://127.0.0.1:9743',    'https': 'https://127.0.0.1:9743'})opener = urllib.request.build_opener(proxy_handler)response = opener.open('http://httpbin.org/get')print(response.read())

比如cookie,这是用来保持自己的登陆状态的,不然每次爬(刷新一次网页),就需要重新登陆相关的信息。

首先需要一个cookijar对象,然后定义一个handler(HTTPCookieProcessor)

import http.cookiejar, urllib.requestcookie = http.cookiejar.CookieJar()handler = urllib.request.HTTPCookieProcessor(cookie)opener = urllib.request.build_opener(handler)response = opener.open('http://www.baidu.com')for item in cookie:    print(item.name+"="+item.value)

下面可以将cookie保存到本地的一个文件。MozillaCookieJar是cookiejar的一个子类。

import http.cookiejar, urllib.requestfilename = "cookie.txt"cookie = http.cookiejar.MozillaCookieJar(filename)handler = urllib.request.HTTPCookieProcessor(cookie)opener = urllib.request.build_opener(handler)response = opener.open('http://www.baidu.com')cookie.save(ignore_discard=True, ignore_expires=True)

urlencode

像一般的get请求都是url网址后面添加一个?然后再跟上参数。所以一个字典形式的参数,可以通过urlencode方法构造成get请求。

from urllib.parse import urlencodeparams = {    'name': 'germey',    'age': 22}base_url = 'http://www.baidu.com?'url = base_url + urlencode(params)print(url)http://www.baidu.com?name=germey&age=22

虽然这个代码大多是复制的,现在放这也是为了以后方便查找,但是urllib,没有requests库好。

原创粉丝点击