urllib 模块 https://www.cnblogs.com/guishou/articles/7089496.html
1.基本方法
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
- url: 需要打开的网址
- data:Post提交的数据
- timeout:设置网站的访问超时时间
直接用urllib.request模块的urlopen()获取页面,page的数据格式为bytes类型,需要decode()解码,转换成str类型。
1 from urllib import request
2 response = request.urlopen(r'http://python.org/') # <http.client.HTTPResponse object at 0x00000000048BC908> HTTPResponse类型
3 page = response.read()
4 page = page.decode('utf-8')
urlopen返回对象提供方法:
- read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作
- info():返回HTTPMessage对象,表示远程服务器返回的头信息
- getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到
- geturl():返回请求的url
2.使用Request
urllib.request.Request(url, data=None, headers={}, method=None)
使用request()来包装请求,再通过urlopen()获取页面。

1 url = r'http://www.lagou.com/zhaopin/Python/?labelWords=label'
2 headers = {
3 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
4 r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
5 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
6 'Connection': 'keep-alive'
7 }
8 req = request.Request(url, headers=headers)
9 page = request.urlopen(req).read()
10 page = page.decode('utf-8')

用来包装头部的数据:
- User-Agent :这个头部可以携带如下几条信息:浏览器名和版本号、操作系统名和版本号、默认语言
- Referer:可以用来防止盗链,有一些网站图片显示来源http://***.com,就是检查Referer来鉴定的
- Connection:表示连接状态,记录Session的状态。
3.Post数据
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
urlopen()的data参数默认为None,当data参数不为空的时候,urlopen()提交方式为Post。

1 from urllib import request, parse
2 url = r'http://www.lagou.com/jobs/positionAjax.json?'
3 headers = {
4 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
5 r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
6 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
7 'Connection': 'keep-alive'
8 }
9 data = {
10 'first': 'true',
11 'pn': 1,
12 'kd': 'Python'
13 }
14 data = parse.urlencode(data).encode('utf-8')
15 req = request.Request(url, headers=headers, data=data)
16 page = request.urlopen(req).read()
17 page = page.decode('utf-8')

urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None)
urlencode()主要作用就是将url附上要提交的数据。

1 data = {
2 'first': 'true',
3 'pn': 1,
4 'kd': 'Python'
5 }
6 data = parse.urlencode(data).encode('utf-8')

经过urlencode()转换后的data数据为?first=true?pn=1?kd=Python,最后提交的url为
http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python
Post的数据必须是bytes或者iterable of bytes,不能是str,因此需要进行encode()编码
1 page = request.urlopen(req, data=data).read()
当然,也可以把data的数据封装在urlopen()参数中
4.异常处理

1 def get_page(url):
2 headers = {
3 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
4 r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
5 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
6 'Connection': 'keep-alive'
7 }
8 data = {
9 'first': 'true',
10 'pn': 1,
11 'kd': 'Python'
12 }
13 data = parse.urlencode(data).encode('utf-8')
14 req = request.Request(url, headers=headers)
15 try:
16 page = request.urlopen(req, data=data).read()
17 page = page.decode('utf-8')
18 except error.HTTPError as e:
19 print(e.code())
20 print(e.read().decode('utf-8'))
21 return page

5、使用代理
urllib.request.ProxyHandler(proxies=None)
当需要抓取的网站设置了访问限制,这时就需要用到代理来抓取数据。

1 data = {
2 'first': 'true',
3 'pn': 1,
4 'kd': 'Python'
5 }
6 proxy = request.ProxyHandler({'http': '5.22.195.215:80'}) # 设置proxy
7 opener = request.build_opener(proxy) # 挂载opener
8 request.install_opener(opener) # 安装opener
9 data = parse.urlencode(data).encode('utf-8')
10 page = opener.open(url, data).read()
11 page = page.decode('utf-8')
12 return page
1.URLError
首先解释下URLError可能产生的原因:
- 网络无连接,即本机无法上网
- 连接不到特定的服务器
- 服务器不存在
在代码中,我们需要用try-except语句来包围并捕获相应的异常。下面是一个例子,先感受下它的风骚
|
1
2
3
4
5
6
7
|
import urllib2
requset = urllib2.Request('http://www.xxxxx.com')
try:
urllib2.urlopen(request)
except urllib2.URLError, e:
print e.reason
|
我们利用了 urlopen方法访问了一个不存在的网址,运行结果如下:
|
1
|
[Errno 11004] getaddrinfo failed
|
它说明了错误代号是11004,错误原因是 getaddrinfo failed
2.HTTPError
HTTPError是URLError的子类,在你利用urlopen方法发出一个请求时,服务器上都会对应一个应答对象response,其中它包含一个数字”状态码”。举个例子,假如response是一个”重定向”,需定位到别的地址获取文档,urllib2将对此进行处理。
其他不能处理的,urlopen会产生一个HTTPError,对应相应的状态吗,HTTP状态码表示HTTP协议所返回的响应的状态。
1. URL解析模块 urlparse
通过Python所带的urlparse模块,我们能够轻松地把URL分解成元件,之后,还能将这些元件重新组装成一个URL。当我们处理HTML 文档的时候,这项功能是非常方便的。
1.1 urlparse.urlparse 函数
此函数会将一个url字符串分解为6个元素,以元祖的形式返回。有的元素可能为空,例:
- >>> from urlparse import urlparse
- >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
- >>> o
- ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
- params='', query='', fragment='')
- >>> o.scheme
- 'http'
- >>> o.port
- 80
- >>> o.geturl()
- 'http://www.cwi.nl:80/%7Eguido/Python.html'
详细的返回值信息:
| Attribute | Index | Value | Value if not present |
|---|---|---|---|
| scheme | 0 | URL scheme specifier | empty string |
| netloc | 1 | Network location part | empty string |
| path | 2 | Hierarchical path | empty string |
| params | 3 | Parameters for last path element | empty string |
| query | 4 | Query component | empty string |
| fragment | 5 | Fragment identifier | empty string |
| username | User name | None | |
| password | Password | None | |
| hostname | Host name (lower case) | None | |
| port | Port number as integer, if present | None |
需要注意的是,传入的URL开头必须要有双斜杠//,否则会被认为是相对路径
1.2 urlparse.urlunparse 函数
此函数作用是把urlparse()分解的元素再拼合还原为一个url,它接收元组(scheme, netloc, path, parameters, query, fragment)后,会重新组成一个具有正确格式的URL,以便供Python的其他HTML解析模块使用。
1.3 urlparse.urlsplit 函数
类似urlparse 函数,不过它的返回列表里面不高括params
1.4 urlparse.urlunsplit 函数
和urlparse.urlsplit 对应,合成URL
1.5 urlparse.urljoin 函数
作用是将一个url替换为另一个url,例:
- >>> from urlparse import urljoin
- >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
- 'http://www.cwi.nl/%7Eguido/FAQ.html'
2. 获取html页面模块urllib
Python所带的urllib和urllib2这两个模块为我们提供了从URL打开并获取数据的功能。
若要通过urllib模块中的urlopen(url [,data])函数打开一个HTML文档,必须提供该文档的URL地址,包括文件名。函数urlopen不仅可以打开位于远程web服务器上的文件,而 且可以打开一个本地文件,并返回一个类似文件的对象,我们可以通过该对象从HTML文档中读出数据。
一旦打开了HTML文档,我们就可以像使用常规文件一样使用read([nbytes])、readline()和readlines()函数来对文件进行读操作。若要读取整个HTML文档的内容的话,您可以使用read()函数,该函数将文件内容作为字符串返回。
打开一个地址之后,您可以使用geturl()函数取得被获取网页的真正的URL。这是很有用的,因为urlopen(或使用的opener对象)也许会伴随一个重定向。获取的网页URL也许和要求的网页URL不一样。
另一个常用的函数是位于从urlopen返回的类文件对象中的info()函数,这个函数可以返回URL位置有关的元数据,比如内容长度、内容类型,等等。
- import urllib2
- def get_html(url):
- html = urllib2.urlopen(url).read()
- return html
2.1 POST方式请求页面
- import urllib2, urllib
- data = {'name' : 'www', 'password' : '123456'} # or [('name','www'),('password','123456'),('item',1),('item',2)] 重复字段
- f = urllib2.urlopen(
- url = 'http://www.ideawu.net/',
- data = urllib.urlencode(data)
- )
- print f.read()
2.2 使用Cookie的情况
- import urllib2
- cookies = urllib2.HTTPCookieProcessor()
- opener = urllib2.build_opener(cookies)
- f = opener.open('http://www.ideawu.net/?act=login&name=user01')
- data = 'Hello'
- request = urllib2.Request(
- url = 'http://www.ideawu.net/?act=send',
- headers = {'Content-Type' : 'text/xml'},
- data = data)
- opener.open(request)
第一次 open() 是进行登录. 服务器返回的 Cookie 被自动保存在 cookies 中, 被用在后来的请求.
第二次 open() 用 POST 方法向服务器发送了 Content-Type=text/xml 的数据. 如果你不创建一个 Request, 而是直接使用 urlopen() 方法, Python 强制把 Content-Type 改为 application/x-www-form-urlencoded.
urllib 模块 https://www.cnblogs.com/guishou/articles/7089496.html的更多相关文章
- 转发自:一像素 十大经典排序算法(动图演示)原链接:https://www.cnblogs.com/onepixel/articles/7674659.html 个人收藏所用 侵删
原链接:https://www.cnblogs.com/onepixel/articles/7674659.html 个人收藏所用 侵删 0.算法概述 0.1 算法分类 十种常见排序算法可 ...
- https://www.cnblogs.com/yuanchenqi/articles/6755717.html
知识预览 一 进程与线程的概念 二 threading模块 三 multiprocessing模块 四 协程 五 IO模型 回到顶部 一 进程与线程的概念 1.1 进程 考虑一个场景:浏览器,网易云音 ...
- 转 jvisualvm 工具使用 https://www.cnblogs.com/kongzhongqijing/articles/3625340.html
VisualVM 是Netbeans的profile子项目,已在JDK6.0 update 7 中自带(java启动时不需要特定参数,监控工具在bin/jvisualvm.exe). https:// ...
- [转帖] SQL参数化的优点 CopyFrom https://www.cnblogs.com/-lzb/articles/4840671.html
梦在远方的小猪 感谢原作者... 后面总结的五点感觉挺好的.. 自己之前的知识点一直没有串起来. 转帖记录一下感谢. sql参数化参数化 说来惭愧,工作差不多4年了,直到前些日子被DBA找上门让我优 ...
- 比较好的Dapper封装的仓储实现类 来源:https://www.cnblogs.com/liuchang/articles/4220671.html
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; usin ...
- Hive和HBase的区别 转载:https://www.cnblogs.com/guoruibing/articles/9894521.html
1.Hive和HBase的区别 1)hive是sql语言,通过数据库的方式来操作hdfs文件系统,为了简化编程,底层计算方式为mapreduce. 2)hive是面向行存储的数据库. 3)Hive本身 ...
- Git命令<转载 https://www.cnblogs.com/cspku/articles/Git_cmds.html>
查看.添加.提交.删除.找回,重置修改文件 git help <command> # 显示command的help git show # 显示某次提交的内容 git show $id gi ...
- python面试题(转自https://www.cnblogs.com/wupeiqi/p/9078770.html)
第一部分 Python基础篇(80题) 为什么学习Python? 通过什么途径学习的Python? Python和Java.PHP.C.C#.C++等其他语言的对比? 简述解释型和编译型编程语言? P ...
- Python内置的urllib模块不支持https协议的解决办法
Django站点使用django_cas接入SSO(单点登录系统),配置完成后登录,抛出“urlopen error unknown url type: https”异常.寻根朔源发现是python内 ...
随机推荐
- vue向路由组件传递props
父子间的组件通讯是通过props和$emit来实现的,那么路由之间的通讯呢,往下看: 我现在再webpack里面有一个这样的结构, 我现在想test1里面的按钮点击跳转到test2里面,获得到test ...
- 当苹果因为UIDevice、udid、uniqueIdentifier而把我们的应用拒之门外invalid binary的时候,呕心沥血解决方法啊
本文转载至 http://blog.csdn.net/macmini/article/details/16341669 当我们辛辛苦苦把应用或者游戏做好的时候,满怀激动地把应用提交上去给苹果大大,谁知 ...
- Windows下IPython安装
1:安装Python, 下载后安装即可:https://www.python.org/downloads/windows/,(选择Python2或Python3) 添加Path环境变量 2:安装ez_ ...
- iPhone 6 Screens Demystified
http://www.paintcodeapp.com/news/iphone-6-screens-demystified
- iOS 引导页面启动一次
#import "AppDelegate.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)a ...
- 1:TwoSum(如果两个和为某个数,找出这俩数的位置)
package leetcode; import java.util.HashMap; import java.util.Map; /** * @author mercy *Example: *Giv ...
- C#中命名空间别名的使用
C#中使用命名空间来分割不同的层级,在不同的层级中可以使用相同的类声明和变量声明.在程序中使用不同命名空间的下的相同名称的类时:可以用一下这几种方法进行限定: 1.使用完全限定名 using Syst ...
- If a cache file exists, it is sent directly to the browser, bypassing the normal system execution.
w开启缓存,缓存视图,用于后续请求. https://www.codeigniter.com/userguide3/overview/appflow.html http://codeigniter.o ...
- 剑指Offer——翻转单词顺序列
题目描述: 牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上.同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思.例如,“studen ...
- Girls' research---hdu3294(回文子串manacher)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3294 给出一个字符串和加密的字符规律 例如 c abcba c代表把串中的c改成a,d改成b... b ...