Python3爬虫笔记 -- urllib

  • urllib库是Python内置的HTTP请求库,不需要额外安装。它包含如下4个模块:
    • request:HTTP请求模块
    • error:异常处理模块
    • parse:提供URL处理方法,包括拆分、解析、合并等
    • robotparser:识别网站等robot.txt文件

1、urllib.request发送请求

  • 连接URL,获取返回页面的源代码;默认请求方式为GET
import urllib.request

response = urllib.request.urlopen('https://www.baidu.com')
print (response.read().decode('utf-8'))

#response是一个HttpResponded对象,其中包含许多方法
print (type(response)) 	
print (response.getheaders())
print (response.getheader('Server'))
  • 使用POST方法提交数据
    使用了data参数之后,请求方式就变成了POST
#byte()方法将数据转化为字节流,其中第一个参数将字典转化为字符串
data = byte(urllib.parse.urlencode({'word':'hello'}), encoding='utf-8')
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
  • 设定超时时间
import socket 
import urllib.request
import urllib.error
try:
	response = urllib.request.urlopen('https://www.baidu.com', timeout=0.1)
except urllib.error.URLError as e:
	if isinstance(e.reason, socket.timeout):
		print ('TIME OUT')
  • Request,
    使用Request,将请求独立成一个对象,还可以更加丰富灵活的配置参数。
    此时data参数必须要上传bytes类型。
url = 'http://httpbin.org/post'
headers = {
    'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
    'Host': 'httpbin.org'
}
dict = {
    'name': 'Germey'
}

data = bytes(parse.urlencode(dict), encoding='utf8')
req = urllib.request.Request(url=url, data=data, headers=headers, method='POST')
response = urllib.request.urlopen(req)

#另外,headers参数也可以用add_headers()方法来添加
req = urllib.request.Request(url=url, data=data, method='POST')
req.add_headers('User-Agent' ,'xxxxxxxxxx')

urllib.request高级用法

  • 利用Handler来创建Opener

验证

from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, build_opener
from urllib.error import URLError

username = 'username'
password = 'password'
url = 'http://localhost:5000/'

p = HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, url, username, password)
auth_handler = HTTPBasicAuthHandler(p)
opener = build_opener(auth_handler)

try:
    result = opener.open(url)
    html = result.read().decode('utf-8')
    print(html)
except URLError as e:
    print(e.reason)

代理

from urllib.error import URLError
from urllib.request import ProxyHandler, build_opener

proxy_handler = ProxyHandler({
    'http': 'http://127.0.0.1:9743',
    'https': 'https://127.0.0.1:9743'
})
opener = build_opener(proxy_handler)
try:
    response = opener.open('https://www.baidu.com')
    print(response.read().decode('utf-8'))
except URLError as e:
    print(e.reason)

Cookies

import http.cookiejar, urllib.request

#注意,获取到的cookie存储在CookieJar对象中
cookie = http.cookiejar.CookieJar()
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以MozillaCookieJar格式保存在文本文档中
filename = 'cookies.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)


#从文本文档中读取LWPCookieJar格式的cookie
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookies.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'))

2、urllib.error处理异常

urllib的error模块定义了由request模块产生的异常。如果出现了问题,request模块便会抛出error模块中定义的异常。

URLError

由request模块生的异常都可以通过捕获这个类来处理。它具有一个属性reason,即返回错误的原因。

from urllib import request, error

try:
    response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:
    print(e.reason)

HTTPError

它是URLError的子类,专门用来处理HTTP请求错误,比如认证请求失败等。它有如下3个属性:

  • code:返回HTTP状态码,比如404表示网页不存在,500表示服务器内部错误等。
  • reason:同父类一样,用于返回错误的原因。
  • headers:返回请求头。
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')

因为URLError是HTTPError的父类,所以可以先选择捕获子类的错误,再去捕获父类的错误,所以上述代码更好的写法如下:

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')

3、urllib.parse解析链接

urlparse()

  • 该方法可以实现URL的识别和分段:
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')
  • urlparse()的API用法:
urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)

urlstring:这是必填项,即待解析的URL。
scheme:它是默认的协议(比如http或https等)。假如这个链接没有带协议信息,会将这个作为默认的协议;假如链接带有协议信息,则这个参数不能更改原链接的协议。
allow_fragments:即是否忽略fragment。如果它被设置为False,fragment部分就会被忽略,它会被解析为path、parameters或者query的一部分,而fragment部分为空。

  • 返回结果ParseResult实际上是一个元组,我们可以用索引顺序来获取,也可以用属性名获取:
from urllib.parse import urlparse
 
result = urlparse('http://www.baidu.com/index.html#comment', allow_fragments=False)
print(result.scheme, result[0], result.netloc, result[1], sep='\n')

urlunparse()

  • urlunparse()接受的参数是一个可迭代对象,但是它的长度必须是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

urlsplit()

  • 这个方法和urlparse()方法非常相似,只不过它不再单独解析params这一部分,只返回5个结果。上面例子中的params会合并到path中。

  • 返回结果是SplitResult,它其实也是一个元组类型,既可以用属性获取值,也可以用索引来获取。

urlunsplit()

  • 与urlunparse()类似,它也是将链接各个部分组合成完整链接的方法,传入的参数也是一个可迭代对象,例如列表、元组等,唯一的区别是长度必须为5。

urljoin()

  • 我们可以提供一个base_url(基础链接)作为第一个参数,将新的链接作为第二个参数,该方法会分析base_url的scheme、netloc和path这3个内容并对新链接缺失的部分进行补充,最后返回结果。
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

可以发现,base_url提供了三项内容scheme、netloc和path。如果这3项在新的链接里不存在,就予以补充;如果新的链接存在,就使用新的链接的部分。而base_url中的params、query和fragment是不起作用的。

urlencode()

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

parse_qs()

有了序列化,必然就有反序列化。如果我们有一串GET请求参数,利用parse_qs()方法,就可以将它转回字典

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()

  • 将内容转化为URL编码的格式。URL中带有中文参数时,有时可能会导致乱码的问题,此时用这个方法可以将中文字符转化为URL编码:
from urllib.parse import quote
 
keyword = '壁纸'
url = 'https://www.baidu.com/s?wd=' + quote(keyword)
print(url)

运行结果:
https://www.baidu.com/s?wd=%E5%A3%81%E7%BA%B8

unquote()

  • 进行URL解码
from urllib.parse import unquote
 
url = 'https://www.baidu.com/s?wd=%E5%A3%81%E7%BA%B8'
print(unquote(url))

运行结果:
https://www.baidu.com/s?wd=壁纸

4、urllib.robotparser分析Robots协议

  • Robots协议也称作爬虫协议、机器人协议,它的全名叫作网络爬虫排除标准(Robots Exclusion Protocol),用来告诉爬虫和搜索引擎哪些页面可以抓取,哪些不可以抓取。它通常是一个叫作robots.txt的文本文件,一般放在网站的根目录下。

  • 当搜索爬虫访问一个站点时,它首先会检查这个站点根目录下是否存在robots.txt文件,如果存在,搜索爬虫会根据其中定义的爬取范围来爬取。如果没有找到这个文件,搜索爬虫便会访问所有可直接访问的页面。

下面的例子实现了对所有搜索爬虫只允许爬取public目录的功能,将上述内容保存成robots.txt文件,放在网站的根目录下,和网站的入口文件(比如index.php、index.html和index.jsp等)放在一起。

User-agent: *
Disallow: /
Allow: /public/

上面的User-agent描述了搜索爬虫的名称,这里将其设置为*则代表该协议对任何爬取爬虫有效。比如,我们可以设置:

User-agent: Baiduspider

这就代表我们设置的规则对百度爬虫是有效的。如果有多条User-agent记录,则就会有多个爬虫会受到爬取限制,但至少需要指定一条。

  • 下面是几个例子:
#禁止所有爬虫访问任何目录的代码如下:
User-agent: * 
Disallow: /

#允许所有爬虫访问任何目录的代码如下:
User-agent: *
Disallow:

#直接把robots.txt文件留空也是可以的。

#禁止所有爬虫访问网站某些目录的代码如下:
User-agent: *
Disallow: /private/
Disallow: /tmp/

#只允许某一个爬虫访问的代码如下:
User-agent: WebCrawler
Disallow:
User-agent: *
Disallow: /

常见搜索爬虫的名称及其对应的网站

在这里插入图片描述

robotparser

  • 可以使用robotparser模块来解析robots.txt。该模块提供了一个类RobotFileParser,它可以根据某网站的robots.txt文件来判断一个爬取爬虫是否有权限来爬取这个网页。
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的时间。
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"))


#也可以在声明RobotFileParser时直接set_url:
rp = RobotFileParser('http://www.jianshu.com/robots.txt')
发布了38 篇原创文章 · 获赞 18 · 访问量 6077

猜你喜欢

转载自blog.csdn.net/Sc0fie1d/article/details/102640954