1.异常处理

URLError类来自urllib库的error模块,它继承自OSError类,是error异常模块的基类,由request模块产生的异常都可以通过这个类来处理。

from urllib import request, error

try:
response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e:
print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e:
print(e.reason)
else:
print('Request Successfully')

输出结果如下:

Not Found
404
Server: nginx/1.10.3 (Ubuntu)
Date: Tue, 09 Apr 2019 07:25:19 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
Vary: Cookie
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Link: <https://cuiqingcai.com/wp-json/>; rel="https://api.w.org/"

* 这样来理解:URLError 和 HTTPError ==> URLError其子类是HTTPError。

*URLError拥有属性reason;HTTPError拥有属性reason(原因)、headers(请求头)、code(状态码).

import socket
import urllib.request
import urllib.error try:
response = urllib.request.urlopen('https://www.baidu.com', timeout=0.01)
except urllib.error.URLError as e:
print(type(e.reason))
if isinstance(e.reason, socket.timeout):
print('TIME OUT')

2.解析链接

urllib库中的parse模块,它定义了处理URL的标准接口,例如实现URL各部分的抽取、合并以及链接转换.

!!! scheme协议://netloc域名/path访问路径;params参数?query查询条件#fragment瞄点

  • urlencode() !!! 这个函数前面提到过,很重要,用于构造get请求参数
from urllib.parse import urlencode

params = {
'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.parse.urlparse(urlstring, scheme='', allow_fragments=True):

*该方法可以实现URL的识别和分段 urlstring必填项,即代解析的URL地址;scheme默认的协议(eg:http、https);allow_fragments是否忽略fragment

实例0:

from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result)

输出结果如下:

<class 'urllib.parse.ParseResult'> ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')

实例1:

from urllib.parse import urlparse

result = urlparse('www.baidu.com/index.html;user?id=5#comment', scheme='https')
print(result) """
输出结果:
ParseResult(scheme='https', netloc='', path='www.baidu.com/index.html', params='user', query='id=5', fragment='comment')
"""

实例2:

from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', scheme='https')
print(result) """
输出结果:
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')
"""

实例3:

from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', allow_fragments=False)
print(result) """
输出结果:
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5#comment', fragment='')
"""

实例4:

from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html#comment', allow_fragments=False)
print(result) """
输出结果:
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html#comment', params='', query='', fragment='')
"""
  • urlunparse(data) :实现URL的构造。长度必须为6、类型:列表、元组或特定的数据结构
from urllib.parse import urlunparse

data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']
print(urlunparse(data)) """
结果如下:
http://www.baidu.com/index.html;user?a=6#comment
"""
  • urljoin():实现链接的解析合并和生成
from urllib.parse import urljoin

print(urljoin('http://www.baidu.com', 'FAQ.html'))
print(urljoin('http://www.baidu.com', 'https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html'))
print(urljoin('http://www.baidu.com/about.html', 'https://cuiqingcai.com/FAQ.html?question=2'))
print(urljoin('http://www.baidu.com?wd=abc', 'https://cuiqingcai.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'))

输出结果如下:

http://www.baidu.com/FAQ.html
https://cuiqingcai.com/FAQ.html
https://cuiqingcai.com/FAQ.html
https://cuiqingcai.com/FAQ.html?question=2
https://cuiqingcai.com/index.php
http://www.baidu.com?category=2#comment
www.baidu.com?category=2#comment
www.baidu.com?category=2

*有点晕?没关系.是有一定规律的,简单来说,有两个参数,以后面的那个为准,没有的补充,有的后者覆盖前者。

*值得注意的是:第一个参数path访问路径后面的(即params、query、fragment)是不起作用的。(看最后的那个打印就明白了)

  • urlsplit():类似与urlparse。区别:urlsplit()会将params合并到path中,返回5个结果,其返回的结果是一个元组类型,即可以用属性获取值,也可以用索引来索取。
from urllib.parse import urlsplit

result = urlsplit('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result)
print(result.scheme,result[0]) """
<class 'urllib.parse.SplitResult'> SplitResult(scheme='http', netloc='www.baidu.com', path='/index.html;user', query='id=5', fragment='comment')
http http
""" from urllib.parse import urlparse result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result) """
<class 'urllib.parse.ParseResult'> ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')
"""
  • urlunsplit():类似与urlunparse。唯一的区别是:传入的参数长度必须为5.
from urllib.parse import urlunsplit

data = ['http', 'www.baidu.com', 'index.html', 'a=6', 'comment']
print(urlunsplit(data)) """
http://www.baidu.com/index.html?a=6#comment
""" from urllib.parse import urlunparse data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']
print(urlunparse(data)) """
http://www.baidu.com/index.html;user?a=6#comment
"""
  • parse_qs():反序列化,将一串Get请求数据转回字典。
from urllib.parse import parse_qs

query = 'name=germey&age=22'
print(parse_qs(query)) """
{'name': ['germey'], 'age': ['22']}
"""
  • parse_qsl():将参数转换为元组组成的列表。
from urllib.parse import parse_qsl

query = 'name=germey&age=22'
print(parse_qsl(query)) """
[('name', 'germey'), ('age', '22')]
"""
  • quote()与unquote():URL编码和解码
from urllib.parse import quote

keyword = "我爱你"
url = 'https://www.baidu.com/s?wd=' + quote(keyword)
print(url) """
https://www.baidu.com/s?wd=%E6%88%91%E7%88%B1%E4%BD%A0
""" from urllib.parse import unquote url = 'https://www.baidu.com/s?wd=%E6%88%91%E7%88%B1%E4%BD%A0'
print(unquote(url)) """
https://www.baidu.com/s?wd=我爱你
"""

3.分析Robots协议(爬虫协议、机器人协议)

*告知爬虫和搜索引擎哪些页面可以爬取,哪些页面不可爬取。它通常是一个叫作robots.txt的文本文件。

举例:robots.txt

  User-agent:* (*指代所有爬虫)

  Disallow: /  (禁止爬取'/'所有目录)

  Allow:/public/ (允许爬取的目录)

*利用urllib的robotparser模块,我们可以实现网站的Robots协议的分析。

==>常用的几个方法:(只例举出3个,其实还有parse()、mtime()、modified(),用到的时候再说)

set_url:设置robots.txt文件的链接。

read():读取robots.txt文件并进行分析.必须调用!!!

can_fetch():参数1 User-agent,参数2 URL.返回结果True.False表明是否可以爬取.

from urllib.robotparser import RobotFileParser
rp = RobotFileParser()
rp.set_url('http://www.jianshu.com/robots.txt')
rp.read()
print(rp.can_fetch('*','http://www.jianshu.com/p/b67554025d7d'))
print(rp.can_fetch('*','http://www.jianshu.com/search?q=python&page=1&type=collections')) """
结果如下:
False
False
"""
# 也可以使用parse()方法执行读取和分析.那个相对复杂,我选择简单的,够用就行.

2.爬虫 urlib库讲解 异常处理、URL解析、分析Robots协议的更多相关文章

  1. 3.爬虫 urlib库讲解 总结

    urllib库的总结: 用ProcessOn(安利这个软件,够用了)根据前面的几节内容做了个思维导图. urllib库一共有四个模块: request:它是最基本的模块,可以用来模拟发送请求 erro ...

  2. 0.爬虫 urlib库讲解 urlopen()与Request()

    # 注意一下 是import urllib.request 还是 form urllib import request 0. urlopen() 语法:urllib.request.urlopen(u ...

  3. 1.爬虫 urlib库讲解 Handler高级用法

    在前面我们总结了urllib库的 urlopen()和Request()方法的使用,在这一小节我们要使用相关的Handler来实现代理.cookies等功能. 写在前面: urlopen()方法不支持 ...

  4. 「Python 编程」编码实现网络请求库中的 URL 解析器

    摘要:怎么写出更短的代码并不是这次要讨论的话题.今天我们来研究一下:运行代码的计算机是如何找到目标服务器的? 相信各位 Python 开发者都用过 Requests 库,有些朋友还用过 WebSock ...

  5. 4.爬虫 requests库讲解 GET请求 POST请求 响应

    requests库相比于urllib库更好用!!! 0.各种请求方式 import requests requests.post('http://httpbin.org/post') requests ...

  6. 5.爬虫 requests库讲解 高级用法

    0.文件上传 import requests files = {'file': open('favicon.ico', 'rb')} response = requests.post("ht ...

  7. 6.爬虫 requests库讲解 总结

    requests库的总结: 用ProcessOn根据前面的几节内容做了个思维导图:

  8. urllib库:分析Robots协议

    1from urllib.robotparser import RobotFileParser 2import ssl 3from urllib.request import urlopen 4ssl ...

  9. 爬虫-Python爬虫常用库

    一.常用库 1.requests 做请求的时候用到. requests.get("url") 2.selenium 自动化会用到. 3.lxml 4.beautifulsoup 5 ...

随机推荐

  1. 网页静态化技术Freemarker

    1.为什么要使用网页静态化技术 网页静态化解决方案在实际开发中运用比较多,例如新闻网站,门户网站中的新闻频道或者是文章类的频道. 对于电商网站的商品详细页来说,至少几百万个商品,每个商品又有大量的信息 ...

  2. ipython notebook开通远程

    之前只是会用,别人告诉我命令和大概怎么设置的,今天自己搭建才发现一知半解搞不定啊. 目的:远程通过ipython notebook调用服务器. 服务器是ubuntu16.04 本地机器win7 配置方 ...

  3. linux各种抓包情况说明

    大家都知道抓包指令:tcpdump    抓包的主要目的是测试端口.网络协议通不通,以及对抓取的数据包进行分析.测试,抓包对熟悉linux的大神都不陌生,网络对于我来说也是一窍不通,只是在这里记录一下 ...

  4. Qt基于model/view数据库编程3

    QSqlQueryModel和QSqlQuery类: 工程开发过程中将这两个类合起来使用,用QSqlQueryModel查询展示数据库中的数据,用QSqlQuery类执行sql语言,实现对数据库的操作 ...

  5. Maven 运行启动时****找不到符号*com.xxx.user.java

    Maven 运行启动时****找不到符号*com.xxx.user.java maven项目更改后没有安装 (install) 重新安装解决问题!

  6. MAC系统如何显示隐藏文件解决方法

    苹果Mac OS 操作系统下,隐藏文件默认为隐藏状态,隐藏文件是否显示有多种方法可以设置. 方法一: 打开终端,输入命令行 1.显示Mac隐藏文件的命令: defaults write com.app ...

  7. php-语言参考-类型3.2-未完待续

    一,PHP变量的8个类型 四种标量类型: boolean (布尔型) integer (整型) float (浮点型, 也称作 double) string (字符串) 两种复合类型: array ( ...

  8. HBase学习(三):数据模型

    和传统的关系型数据库类似,HBase以表(Table)的方式组织数据.HBase的表由行(Row)和列(Column)共同构成,与关系型数据库不同的是HBase有一个列族(ColumnFamily)的 ...

  9. jmeter测试报告优化

    1.下载jmeter.results.shanhe.me.xsl 将该文件拷贝到jmeter\extras目录下 2.修改jmeter.results.shanhe.me.xsl 这里直接拷贝 jme ...

  10. AtCoder AGC028-F:Reachable Cells

    越来越喜欢AtCoder了,遍地都是神仙题. 题意: 给定一个\(N\)行\(N\)列的迷宫,每一个格子要么是障碍,要么是空地.每一块空地写着一个数码.在迷宫中,每一步只允许向右.向下走,且只能经过空 ...