6、解析链接(urllib.parse)
urllib库里还提供了parse这个模块,它定义了处理URL的标准接口,例如实现URL各部分的抽取、合并以及链接转换。
6.1 urlparse()
该方法可以实现URL的识别和分段,
Copy from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result)
输出
Copy <class 'urllib.parse.ParseResult'>
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')
可以看到,返回结果是一个ParseResult类型的对象,它包含6部分,分别是scheme、netloc、path、params、query和fragment。
标准的链接格式如下
Copy scheme://netloc/path;parameters?query#fragment
除此之外,urlparse的API用法如下
Copy urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
allow_fragments:是否忽略fragment,当设置为False时,会忽略。这个时候原来的fragment的部分会变为前面path、parameters或query的一部分。
6.2 urlunparse()
与urlparse的功能相反,合并链接各部分的信息
Copy from urllib.parse import urlunparse
data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']
print(urlunparse(data))
输出
Copy http://www.baidu.com/index.html;user?a=6#comment
6.3 urlsplit()
这个方法和urlparse()方法非常相似,只不过它不再单独解析params这一部分,只返回5个结果。上面例子中的params会合并到path中。
Copy from urllib.parse import urlsplit
result = urlsplit('http://www.baidu.com/index.html;user?id=5#comment')
print(result)
print((result.scheme, result[0])
输出
Copy SplitResult(scheme='http', netloc='www.baidu.com', path='/index.html;user', query='id=5', fragment='comment')
http http
6.4 urlunsplit()
与urlunparse()类似,它也是将链接各个部分组合成完整链接的方法,传入的参数也是一个可迭代对象,例如列表、元组等,唯一的区别是长度必须为5。
Copy from urllib.parse import urlunsplit
data = ['http', 'www.baidu.com', 'index.html', 'a=6', 'comment']
print(urlunsplit(data))
输出
Copy http://www.baidu.com/index.html?a=6#comment
6.5 urljoin()
有了urlunparse()和urlunsplit()方法,我们可以完成链接的合并,不过前提必须要有特定长度的对象,链接的每一部分都要清晰分开。
此外,生成链接还有另一个方法,那就是urljoin()方法。我们可以提供一个base_url(基础链接)作为第一个参数,将新的链接作为第二个参数,该方法会分析base_url的scheme、netloc和path这3个内容并对新链接缺失的部分进行补充,最后返回结果。
Copy 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'))
输出
Copy 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
可以发现,base_url提供了三项内容scheme、netloc和path。如果这3项在新的链接里不存在,就予以补充;如果新的链接存在,就使用新的链接的部分。而base_url中的params、query和fragment是不起作用的。
通过urljoin()方法,我们可以轻松实现链接的解析、拼合与生成。
6.6 urlencode()
主要用于构造GET请求参数
Copy from urllib.parse import urlencode
params = {
'name': 'germey',
'age': 22
}
base_url = 'http://www.baidu.com?'
url = base_url + urlencode(params)
print(url)
输出
Copy http://www.baidu.com?name=germey&age=22
6.7 parse_qs()
反序列化,如果我们有一串GET请求参数,利用parse_qs()方法,就可以将它转回字典
Copy from urllib.parse import parse_qs
query = 'name=germey&age=22'
print(parse_qs(query))
输出
Copy {'name': ['germey'], 'age': ['22']}
6.8 parse_qsl()
将参数转化为元组组成的列表
Copy from urllib.parse import parse_qsl
query = 'name=germey&age=22'
print(parse_qsl(query))
输出
Copy [('name', 'germey'), ('age', '22')]
6.9 quote()
该方法可以将内容转化为URL编码的格式。URL中带有中文参数时,有时可能会导致乱码的问题,此时用这个方法可以将中文字符转化为URL编码,
Copy from urllib.parse import quote
keyword = '壁纸'
url = 'https://www.baidu.com/s?wd=' + quote(keyword)
print(url)
6.10 unquote()
有了quote()方法,当然还有unquote()方法,它可以进行URL解码,
Copy from urllib.parse import unquote
url = 'https://www.baidu.com/s?wd=%E5%A3%81%E7%BA%B8'
print(unquote(url))
输出
Copy https://www.baidu.com/s?wd=壁纸
7、分析Robots协议
利用urllib的robotparser模块,我们可以实现网站Robots协议的分析。
7.1 Robots协议
Robots协议也称作爬虫协议、机器人协议,它的全名叫作网络爬虫排除标准(Robots Exclusion Protocol),用来告诉爬虫和搜索引擎哪些页面可以抓取,哪些不可以抓取。它通常是一个叫作robots.txt的文本文件,一般放在网站的根目录下。
当搜索爬虫访问一个站点时,它首先会检查这个站点根目录下是否存在robots.txt文件,如果存在,搜索爬虫会根据其中定义的爬取范围来爬取。如果没有找到这个文件,搜索爬虫便会访问所有可直接访问的页面。
robots.txt示例
Copy User-agent: *
Disallow: /
Allow: /public/
这实现了对所有搜索爬虫只允许爬取public目录的功能,将上述内容保存成robots.txt文件,放在网站的根目录下,和网站的入口文件 (比如index.php、index.html和index.jsp等)放在一起。
上面的User-agent描述了搜索爬虫的名称,这里将其设置为*则代表该协议对任何爬取爬虫有效。
Copy User-agent: Baiduspider
这就代表我们设置的规则对百度爬虫是有效的。如果有多条User-agent记录,则就会有多个爬虫会受到爬取限制,但至少需要指定一条。
Disallow指定了不允许抓取的目录,比如上例子中设置为/则代表不允许抓取所有页面。
Allow一般和Disallow一起使用,一般不会单独使用,用来排除某些限制。现在我们设置为/public/,则表示所有页面不允许抓取,但可以抓取public目录。
其他示例
Copy # 禁止所有爬虫访问任何目录
User-agent: *
Disallow: /
# 允许所有爬虫访问任何目录
User-agent: *
Disallow:
# 禁止所有爬虫访问网站某些目录
User-agent: *
Disallow: /private/
Disallow: /tmp/
# 只允许某一个爬虫访问
User-agent: WebCrawler
Disallow:
User-agent: *
Disallow: /
7.2 爬虫名称
爬虫是有固定名字的
7.3 robotparser
了解Robots协议之后,我们就可以使用robotparser模块来解析robots.txt了。该模块提供了一个类RobotFileParser,它可以根据某网站的robots.txt文件来判断一个爬取爬虫是否有权限来爬取这个网页。
Copy urllib.robotparser.RobotFileParser(url='')
方法
set_url():用来设置robots.txt文件的链接。如果在创建RobotFileParser对象时传入了链接,那么就不需要再使用这个方法设置了。
read():读取robots.txt文件并进行分析。注意,这个方法执行一个读取和分析操作,如果不调用这个方法,接下来的判断都会为False,所以一定记得调用这个方法。这个方法不会返回任何内容,但是执行了读取操作。
parse():用来解析robots.txt文件,传入的参数是robots.txt某些行的内容,它会按照robots.txt的语法规则来分析这些内容。
can_fetch():该方法传入两个参数,第一个是User-agent,第二个是要抓取的URL。返回的内容是该搜索引擎是否可以抓取这个URL,返回结果是True或False。
mtime():返回的是上次抓取和分析robots.txt的时间,这对于长时间分析和抓取的搜索爬虫是很有必要的,你可能需要定期检查来抓取最新的robots.txt。
modified():它同样对长时间分析和抓取的搜索爬虫很有帮助,将当前时间设置为上次抓取和分析robots.txt的时间。
实例
Copy 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"))
输出
使用parse()方法
Copy from urllib.robotparser import RobotFileParser
from urllib.request import urlopen
rp = RobotFileParser()
rp.parse(urlopen('http://www.jianshu.com/robots.txt').read().decode('utf-8').split('\n'))
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"))
输出一样结果
小结:
robots.txt文件是一个很有用的文件,在爬虫时应该如何使用它呢?