Python爬虫--Urllib库
Urllib库
Urllib是python内置的HTTP请求库,包括以下模块:urllib.request (请求模块)、urllib.error( 异常处理模块)、urllib.parse (url解析模块)、urllib.robotparser (robots.txt解析模块)
一、urllib.request 请求模块
1、urllib.request.urlopen
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
注: urlopen一般常用的有三个参数,它的参数如下:
urllib.requeset.urlopen(url,data,timeout)
1.1、url参数:
import urllib.request response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))
1.2、data参数:
import urllib.parse
import urllib.request data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
print(data)
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())
注:这里就用到urllib.parse,通过bytes(urllib.parse.urlencode())可以将post数据进行转换放到urllib.request.urlopen的data参数中。这样就完成了一次post请求。所以如果添加data参数的时候就是以post请求方式请求,如果没有data参数就是get请求方式
1.3、timeout参数
在某些网络情况不好或者服务器端异常的情况会出现请求慢的情况,或者请求异常,所以这个时候我们需要给请求设置一个超时时间,而不是让程序一直在等待结果
import urllib.request response = urllib.request.urlopen('http://httpbin.org/get', timeout=1)
print(response.read())
1.4、响应类型、状态码、响应头
import urllib.request response = urllib.request.urlopen('https://www.python.org')
print(type(response))
print(response.status) #获取状态码
print(response.getheaders().response.getheader("server")) #获取头部信息
print(response.read()) #获取响应体的内容
上述的urlopen只能用于一些简单的请求,因为它无法添加一些header信息,如果后面写爬虫我们可以知道,很多情况下我们是需要添加头部信息去访问目标站的,这个时候就用到了urllib.request
2、urllib.request.Request
2.1、request.Request 示例:
import urllib.request request = urllib.request.Request('https://python.org')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
2.2、设置headers(请求头)
有很多网站为了防止程序爬虫爬网站造成网站瘫痪,会需要携带一些headers头部信息才能访问
from urllib import request, parse url = 'http://httpbin.org/post'
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Host': 'httpbin.org'
}
dict = {
'name': 'QQ'
}
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'))
通过add_header设置请求头:
from urllib import request, parse url = 'http://httpbin.org/post'
dict = {
'name': QQ'
}
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'))
2.3、设置代理
通过rulllib.request.ProxyHandler()可以设置代理,网站它会检测某一段时间某个IP 的访问次数,如果访问次数过多,它会禁止你的访问,所以这个时候需要通过设置代理来爬取数据
import urllib.request proxy_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())
2.4、设置cookie
cookie中保存中我们常见的登录信息,有时候爬取网站需要携带cookie信息访问
import http.cookiejar, urllib.request
cookie = http.cookiejar.CookieJar() #用于获取cookie以及存储cookie
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可以写入到文件中保存,有两种方式http.cookiejar.MozillaCookieJar和http.cookiejar.LWPCookieJar()
import http.cookiejar, urllib.request
filename = "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)
http.cookiejar.MozillaCookieJar()方式
import http.cookiejar, urllib.request
filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar(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)
http.cookiejar.LWPCookieJar()方式
同样的如果想要通过获取文件中的cookie获取的话可以通过load方式,哪种方式写入的,就用哪种方式读取
import http.cookiejar, urllib.request
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))
load
二、urllib.error 异常处理模块
在很多时候我们通过程序访问页面的时候,有的页面可能会出现错误,类似404,500等错误,这个时候就需要我们捕捉异常:
1、URLError :reason属性,抓异常的时候只能打印错误信息
from urllib import request,error try:
response = request.urlopen("http://pythonsite.com/1111.html")
except error.URLError as e:
print(e.reason)
import socket from urllib import error,request try:
response = request.urlopen("http://www.pythonsite.com/",timeout=0.001)
except error.URLError as e:
print(type(e.reason))
if isinstance(e.reason,socket.timeout):
print("time out")
使用reason深入判断
2、HTTPError(HTTPError是URLError的子类)里有三个属性:code,reason,headers
from urllib import request,error
try:
response = request.urlopen("http://pythonsite.com/1111.html")
except error.HTTPError as e:
print(e.reason)
print(e.code)
print(e.headers)
except error.URLError as e:
print(e.reason) else:
print("reqeust successfully")
三、urllib.parse url解析模块
1、urlparse
将URL字符串拆分,然后以元组的形式展示。
from urllib.parse import urlparse result = urlparse("http://www.baidu.com/index.html;user?id=5#comment")
print(result) #同时我们是可以指定协议类型:
result = urlparse("www.baidu.com/index.html;user?id=5#comment",scheme="https")
#这样拆分的时候协议类型部分就会是指定的部分,当然如果url里面已经带了协议,再通过scheme指定的协议就不会生效
2、urlunpars
将字符串拼接成url
from urllib.parse import urlunparse data = ['http','www.baidu.com','index.html','user','a=123','commit']
print(urlunparse(data))
3、urljoin
同样用于拼接字符串
from urllib.parse import urljoin print(urljoin('http://www.baidu.com', 'FAQ.html'))
print(urljoin('http://www.baidu.com', 'https://pythonsite.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://pythonsite.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://pythonsite.com/FAQ.html?question=2'))
print(urljoin('http://www.baidu.com?wd=abc', 'https://pythonsite.com/index.php'))
print(urljoin('http://www.baidu.com', '?category=2#comment'))
print(urljoin('www.baidu.com', '?category=2#comment'))
print(urljoin('www.baidu.com#comment', '?category=2'))
4、urlencode
这个方法可以将字典转换为url参数
from urllib.parse import urlencode params = {
"name":"QQ",
"age":12,
}
base_url = "http://www.baidu.com?" url = base_url+urlencode(params)
print(url)
Python爬虫--Urllib库的更多相关文章
- Python爬虫Urllib库的高级用法
Python爬虫Urllib库的高级用法 设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Head ...
- Python爬虫Urllib库的基本使用
Python爬虫Urllib库的基本使用 深入理解urllib.urllib2及requests 请访问: http://www.mamicode.com/info-detail-1224080.h ...
- python爬虫 - Urllib库及cookie的使用
http://blog.csdn.net/pipisorry/article/details/47905781 lz提示一点,python3中urllib包括了py2中的urllib+urllib2. ...
- 对于python爬虫urllib库的一些理解(抽空更新)
urllib库是Python中一个最基本的网络请求库.可以模拟浏览器的行为,向指定的服务器发送一个请求,并可以保存服务器返回的数据. urlopen函数: 在Python3的urllib库中,所有和网 ...
- python爬虫---urllib库的基本用法
urllib是python自带的请求库,各种功能相比较之下也是比较完备的,urllib库包含了一下四个模块: urllib.request 请求模块 urllib.error 异常处理模块 u ...
- python爬虫 urllib库基本使用
以下内容均为python3.6.*代码 学习爬虫,首先有学会使用urllib库,这个库可以方便的使我们解析网页的内容,本篇讲一下它的基本用法 解析网页 #导入urllib from urllib im ...
- Python爬虫urllib库的使用
urllib 在Python2中,有urllib和urllib2两个库实现请求发送,在Python3中,统一为urllib,是Python内置的HTTP请求库 request:最基本的HTTP请求模块 ...
- Python爬虫 Urllib库的高级用法
1.设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Headers 的属性. 首先,打开我们的浏览 ...
- python爬虫urllib库使用
urllib包括以下四个模块: 1.request:基本的HTTP请求模块,可以用来模拟发送请求.就像在浏览器里输入网址然后回车一样,只需要给库方法传入URL以及额外的参数,就可以模拟实现这个过程. ...
随机推荐
- 10.1综合强化刷题 Day7
noip提高组模拟赛 ...
- Network | CIDR
无类别(现在) 无类别域间路由(Classless Inter-Domain Routing.CIDR)是一个用于给用户分配IP地址以及在互联网上有效地路由IP数据包的对IP地址进行归类的方法. CI ...
- 获取Android系统默认给每个app分配的内存上限
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); int ...
- 经验分享 | Burpsuite抓取非HTTP流量
使用Burp对安卓应用进行渗透测试的过程中,有时候会遇到某些流量无法拦截的情况,这些流量可能不是HTTP协议的,或者是“比较特殊”的HTTP协议(以下统称非HTTP流量).遇到这种情况,大多数人会选择 ...
- Web编程前端之7:web.config详解 【转】
http://www.cnblogs.com/alvinyue/archive/2013/05/06/3063008.html 声明:这篇文章是摘抄周公(周金桥)的<asp.net夜话> ...
- Octave入门基础
Octave入门基础 一.简单介绍 1.1 Octave是什么? Octave是一款用于数值计算和画图的开源软件.和Matlab一样,Octave 尤其精于矩阵运算:求解联立方程组.计算矩阵特征值和特 ...
- 谈 API 的撰写 - 子系统
在做一个系统时,有一些子系统几乎是必备的:配置管理,CLI,以及测试框架. 配置管理 我们先说配置管理.一个系统的灵活度,和它的配置管理是离不开的.系统中存在的大量的预置的属性(下文简称 proper ...
- 重装系统后恢复wubi安装的Ubuntu(未实测)
wubi安装成功,但是后来windows系统重装了,如何修复ubuntu系统的引导?[另外完全可以复制别人的wubi安装的ubuntu,但是要放在同一个盘符下] 将X:/ubuntu/winboo ...
- 编译-O 选项对性能提升作用
GCC -O 选项 这个选项控制所有的优化等级.使用优化选项会使编译过程耗费更多的时间,并且占用更多的内存,尤其是在提高优化等级的时候. -O设置一共有五种:-O0.-O1.-O2.-O3和-Os. ...
- 说说我的web前端之路,分享些前端的好书(转)
WEB前端研发工程师,在国内算是一个朝阳职业,这个领域没有学校的正规教育,大多数人都是靠自己自学成才.本文主要介绍自己从事web开发以来(从大二至今)看过的书籍和自己的成长过程,目的是给想了解Java ...