Python 爬虫 --- urllib
对于互联网数据,Python 有很多处理网络协议的工具,urllib 是很常用的一种。
一、urllib.request,request 可以很方便的抓取 URL 内容。
- urllib.request.urlopen(url) 返回请求 url 后的二进制对象·
参数:url=‘http://www.baidu.com’,请求的 url。
data=None,请求的数据,可有可无,bytes 类型。
timeout=3,设置访问超时时间,可有可无
cafile=None,HTTPS 请求 CA 证书
capath=None,CA 证书 path
context=None,指定 SSL 设置,可有可无,ssl.SSLContext 类型
- urllib.request.Request() 把请求独立成一个对象,对请求参数的设定更方便灵活
参数:url,请求 url。
data=None,请求参数,可有可无
headers={},请求 header 参数。
origin_req_host=None,请求 host 或 IP
unverifiable=False,表明请求是否无法验证,默认为 false
method=None,请求方法,get、post、put 等
- urllib.request.ProxyHandler() 设置代理,参数为 dict,如:{ 'http': '120.194.18.90:81'}
- urllib.request.build_opener() 构建 Opener,参数为上面设置的代理
- urllib.request.install_opener() 安装 Opener,参数为上面构建的 opener
- urllib.request.HTTPCookieProcessor() cookie 操作,参数为 http.cookiejar.CookieJar() 得到的 cookie
from urllib import request,parse #url
url = 'http://fanyi.baidu.com/sug' #request data
data = {'kw': 'python'}
data = parse.urlencode(data).encode('utf-8') #proxy
proxy = {'http': '120.194.18.90:81'}
proxy_handler = request.ProxyHandler(proxy)
opener = request.build_opener(proxy_handler)
request.install_opener(opener) #headers = {
# 'Content-Length': len(data),
# 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0'
#} #req = request.Request(url=base_url, data=data, headers=headers)
req = request.Request(base_url, data) req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0') rsp = request.urlopen(req) result = rsp.read().decode('utf-8') print(result)
#rsp 的属性
print('返回数据类型: {}'.format(type(rsp))) print('返回数据信息: {}'.format(rsp)) print('header 信息: {}'.format(rsp.info())) print('header 信息: {}'.format(rsp.getheaders())) print('header 属性信息: {}'.format(rsp.getheader('Server'))) print('响应状态信息: {}'.format(rsp.status)) print('响应状态信息: {}'.format(rsp.getcode())) print('响应的 URL: {}'.format(rsp.geturl()))
#cookie 操作 from urllib import request
from http impot cookiejar #获取 cookie
cookie = cookiejar.CookieJar()
handler = request.HTTPCookieProcessor(cookie)
opener = request.build_opener(handler) rsp = opener.open('http://www.baidu.com')
res = rsp.read().decode('utf-8') print(res) #保存 cookie
#FileCookieJar、MozillaCookieJar、LWPCookieJar,不同的保存格式
filename = 'cookie.txt'
cookie = cookiejar.MozillaCookieJar(filename)
handler = request.HTTPCookieProcessor(cookie)
opener = request.build_opener(handler) rsp = opener.open('http://www.baidu.com') cookie.save(igonre_discard=True, ignore_expires=True) #使用 cookie
cookie cookiejar.MozillaCookieJar()
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
handler = request.HTTPCookieProcessor(cookie)
opener = request.build_opener(handler)
rsp = opener.open('http://www.baidu.com') res = rsp.read().decode('utf-8')
print(res)
二、urllib.parse
- urllib.parse.urlparse() 将 URL 解析成元组形式
参数:
url,访问 url
scheme,解析协议,https、http
allow_fragments=False,是够带有查询参数
- urllib.parse.urlunparse() 将元组拼接成完整 url
- urllib.parse.urljoin() 拼接 url
#
url = 'https://www.baidu.com/s?'
qs = {'wd':'python'} qs = urllib.parse.urlparse(qs)
full_url = url + qs #
url = urllib.parse.urlparse('http://www.baidu.com/s?wd=python')
print(url) #
data = ['http', 'www.baidu.com', 's', 'wd=python']
print(urllib.parse.urlunparse(data)) #
print(urllib.parse.urljson('http://www.baidu.com', 'index.html'))
三、urllib.error
通过 try...except 可以捕捉异常,error 分为 HTTPError,URLError
try:
res = urllib.request.urlopen(url).open().decode('utf-8')
print(res)
except urllib.error.URLError as e:
print(e)
except urllib.error.HTTPError as e:
print(e)
except Exception as e:
print(e)
四、urllib.robotparser
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模块url编码处理
案例:爬取使用搜狗根据指定词条搜索到的页面数据(例如爬取词条为‘周杰伦'的页面数据) import urllib.request # 1.指定url url = 'https://www.sogou. ...
- python 爬虫 urllib模块 目录
python 爬虫 urllib模块介绍 python 爬虫 urllib模块 url编码处理 python 爬虫 urllib模块 反爬虫机制UA python 爬虫 urllib模块 发起post ...
- python爬虫 - Urllib库及cookie的使用
http://blog.csdn.net/pipisorry/article/details/47905781 lz提示一点,python3中urllib包括了py2中的urllib+urllib2. ...
- Python爬虫urllib模块
Python爬虫练习(urllib模块) 关注公众号"轻松学编程"了解更多. 1.获取百度首页数据 流程:a.设置请求地址 b.设置请求时间 c.获取响应(对响应进行解码) ''' ...
- python爬虫-urllib模块
urllib 模块是一个高级的 web 交流库,其核心功能就是模仿web浏览器等客户端,去请求相应的资源,并返回一个类文件对象.urllib 支持各种 web 协议,例如:HTTP.FTP.Gophe ...
- 对于python爬虫urllib库的一些理解(抽空更新)
urllib库是Python中一个最基本的网络请求库.可以模拟浏览器的行为,向指定的服务器发送一个请求,并可以保存服务器返回的数据. urlopen函数: 在Python3的urllib库中,所有和网 ...
- Python爬虫--Urllib库
Urllib库 Urllib是python内置的HTTP请求库,包括以下模块:urllib.request (请求模块).urllib.error( 异常处理模块).urllib.parse (url ...
随机推荐
- go-simplejson文档学习
https://godoc.org/github.com/bitly/go-simplejson 导入方式: import "github.com/bitly/go-simplejson&q ...
- 淘宝可伸缩高性能互联网架构HSF(转)
文章转自http://blog.csdn.net/hpf911/article/details/14165865 时间过得很快,来淘宝已经两个月了,在这两个月的时间里,自己也感受颇深.下面就结合淘宝目 ...
- ftp、ssh
ftp.ssh都是网络传输的协议,两者一般用来访问服务器,支持ftp的服务器称为ftp服务器,支持ssh的服务器称为ssh服务器. 说白了就是不同的访问方式,ssh更加安全,有相应的密匙 https: ...
- [07] 使用注解完成IOC配置
1.扫描配置 之前使用的Spring的Bean管理都是通过xml的配置文件来操作的,在Spring3.0之后已经引入了注解形式,Spring可以在指定路径下进行扫描,寻找标注了@Component.@ ...
- 3.1《想成为黑客,不知道这些命令行可不行》(Learn Enough Command Line to Be Dangerous)——下载文件
首先,为了不手动创建一个长文件(这太麻烦了),我们将使用强大的curl(有时也写作"cURL")工具从网上下载一个文件,这个命令可以让命令行与URL交互.尽管这不是Unix核心命令 ...
- Luogu4770 NOI2018 你的名字 SAM、主席树
传送门 UPD:发现之前被smy误导的一个细节,改过来之后就AC了-- 一道比较套路的SAM题,虽然我连套路都不会-- 先考虑前\(68pts\),也就是\(l=1 , r=|S|\)的情况.我们对\ ...
- WPF中TreeView.BringIntoView方法的替代方案
原文:WPF中TreeView.BringIntoView方法的替代方案 WPF中TreeView.BringIntoView方法的替代方案 周银辉 WPF中TreeView.BringIntoVie ...
- 2-SAT超入门讲解
Preface 说实话2-SAT的题目我都没怎么做过,所以这里讲的都是些超入门什么的 还有一些板子题,由于是暑假的时候学的所以有些我也记不清了 主要学习参考自:Mancher的课件&& ...
- Python 学习 第四篇:动态类型模型
Python的变量不用声明,赋值之后就可以直接使用,类型是在运行过程中自动确定的,这就是动态类型模型.该模型把变量和对象设计成两个不同的实体,对象是存储数据的地方,对象的类型是由初始值自动决定的,而变 ...
- Visual Studio 2019 Serial Keys
Visual Studio 2019 Enterprise BF8Y8-GN2QH-T84XB-QVY3B-RC4DF Visual Studio 2019 Professional NYWVH-HT ...