如何全面掌握Python爬虫urllib库的常用方法及用法?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1127个文字,预计阅读时间需要5分钟。
Urllib官方文档地址:https://docs.python.org/3/library/urllib.
urllib提供了一系列用于操作URL的功能。主要包括以下内容:
- urllib.request:用于发送HTTP请求、获取响应等。- urllib.parse:用于解析URL、构建URL等。- urllib.error:定义了urllib库中可能出现的错误。
以下是urllib库中一些常用方法的简单介绍:
1. urllib.request.urlopen(url):打开指定的URL,并返回一个HTTPResponse对象。
2.urllib.request.urlopen(url, data=None):打开指定的URL,并带上POST数据(data)。
3.urllib.parse.urlparse(url):解析URL,返回一个ParseResult对象。
4.urllib.parse.urlunparse(parsed_url):将ParseResult对象转换回URL字符串。
更多详细内容,请参考官方文档。
Urllib
官方文档地址:docs.python.org/3/library/urllib.html
urllib提供了一系列用于操作URL的功能。
本文主要介绍的是关于python urllib库常用方法用法的相关内容,下面话不多说了,来一起看看详细的介绍吧
1、读取cookies
import www.bigdata17.com') for item in cookie: print(item.name + "=" + item.value)
2、将cookies保存在文件中
filename = 'baidu_cookies.txt' cookies = cj.MozillaCookieJar(filename) handler = request.HTTPCookieProcessor(cookies) opener = request.build_opener(handler) response = opener.open('www.baidu.com') cookies.save(ignore_discard=True,ignore_expires=True)
3、处理异常
URLError和HTTPError类,两个类是父子关系,HTTPError会返回错误代码,两个类都可以处理request模块产生的异常,这两个都有一个reason属性,用于记录出现异常的原因
URLError处理异常:
from urllib import request,error try: response = request.urlopen('www.bigdata17.com/index.htm') except error.URLError as e: print(e.reason)
HTTPError处理异常:
这个类是专门处理www.bigdata17.com/index.htm') except error.HTTPError as e: print(e.reason) print(e.code) print(e.headers)
4、解析链接
urllib库中的parse类提供了很多用于解析链接的方法。
urlparse()方法是专门用于解析链接的,我们先看这个方法的返回值:
from urllib.parse import urlparse result = urlparse('www.bigdata17.com') print(result)
上面的代码返回的结果:
ParseResult(scheme='www.bigdata17.com/22.html;user=bigdata17?id=10#content') print(result)
运行的结果如下:
ParseResult(scheme='止,是scheme。从://开始到一个/位置,是netloc域名。从/开始到;分号为止是path,访问页面的路径。;开始到?为止是params参数。从?问号开始到#井号结束时query查询参数。最后是fragment锚点参数。
5、urlopen()方法
该方法返回的是HTTPResponse对象:
import urllib.request as request response = request.urlopen('www.bigdata17.com') print(response) <www.bigdata17.com') print(response.read().decode('utf-8'))
使用该方法时要注意网站使用的编码格式,配合decode()方法一起使用,否则会出现乱码。像百度用的是utf-8,网易用的是gbk。
getHeaders()方法返回的是网页的头信息:
import urllib.request as request response = request.urlopen('www.bigdata17.com') print(response.getheaders())
结果:
[('Server', 'nginx/1.12.2'), ('Date', 'Mon, 12 Nov 2018 15:45:22 GMT'), ('Content-Type', 'text/html'), ('Content-Length', '38274'), ('Last-Modified', 'Thu, 08 Nov 2018 00:35:52 GMT'), ('Connection', 'close'), ('ETag', '"5be384e8-9582"'), ('Accept-Ranges', 'bytes')]
继续看urlopen()方法有哪些参数:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
其中url是必须传递的参数,其他的参数不是必须传递的。data用于将数据传输到我们要爬取的网站上,例如用户名、密码、验证码等。timeout是设置请求超时时间。
data参数的用法:
>>> import urllib.parse as parse >>> import urllib.request as request >>> data = bytes(parse.urlencode({'username': 'bigdata17'}), encoding='utf8') >>> print(data) b'username=bigdata17' >>> response = request.urlopen('www.bigdata17.com', timeout=1) print(response.read())
如果将timeout设置为0.01,则会报如下的错误:
socket.timeout: timed out
During handling of the above exception, another exception
设置请求头信息:
请求的头信息一般对带有浏览器的信息,很多网站根据请求头信息来判断该请求是正常的浏览器发起的还是由爬虫发起的。设置爬虫头信息方法:
from urllib import request, parse url = 'www.bigdata17.com:3128/'}) proxy_auth_handler = urllib.request.ProxyBasicAuthHandler() proxy_auth_handler.add_password('realm', 'host', 'username', 'password') opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler) # This time, rather than install the OpenerDirector, we use it directly: opener.open('accounts.douban.com/login?alias=&redir=https%3A%2F%2Fwww.douban.com%2F&source=index_nav&error=1001')
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易盾网络的支持。
本文共计1127个文字,预计阅读时间需要5分钟。
Urllib官方文档地址:https://docs.python.org/3/library/urllib.
urllib提供了一系列用于操作URL的功能。主要包括以下内容:
- urllib.request:用于发送HTTP请求、获取响应等。- urllib.parse:用于解析URL、构建URL等。- urllib.error:定义了urllib库中可能出现的错误。
以下是urllib库中一些常用方法的简单介绍:
1. urllib.request.urlopen(url):打开指定的URL,并返回一个HTTPResponse对象。
2.urllib.request.urlopen(url, data=None):打开指定的URL,并带上POST数据(data)。
3.urllib.parse.urlparse(url):解析URL,返回一个ParseResult对象。
4.urllib.parse.urlunparse(parsed_url):将ParseResult对象转换回URL字符串。
更多详细内容,请参考官方文档。
Urllib
官方文档地址:docs.python.org/3/library/urllib.html
urllib提供了一系列用于操作URL的功能。
本文主要介绍的是关于python urllib库常用方法用法的相关内容,下面话不多说了,来一起看看详细的介绍吧
1、读取cookies
import www.bigdata17.com') for item in cookie: print(item.name + "=" + item.value)
2、将cookies保存在文件中
filename = 'baidu_cookies.txt' cookies = cj.MozillaCookieJar(filename) handler = request.HTTPCookieProcessor(cookies) opener = request.build_opener(handler) response = opener.open('www.baidu.com') cookies.save(ignore_discard=True,ignore_expires=True)
3、处理异常
URLError和HTTPError类,两个类是父子关系,HTTPError会返回错误代码,两个类都可以处理request模块产生的异常,这两个都有一个reason属性,用于记录出现异常的原因
URLError处理异常:
from urllib import request,error try: response = request.urlopen('www.bigdata17.com/index.htm') except error.URLError as e: print(e.reason)
HTTPError处理异常:
这个类是专门处理www.bigdata17.com/index.htm') except error.HTTPError as e: print(e.reason) print(e.code) print(e.headers)
4、解析链接
urllib库中的parse类提供了很多用于解析链接的方法。
urlparse()方法是专门用于解析链接的,我们先看这个方法的返回值:
from urllib.parse import urlparse result = urlparse('www.bigdata17.com') print(result)
上面的代码返回的结果:
ParseResult(scheme='www.bigdata17.com/22.html;user=bigdata17?id=10#content') print(result)
运行的结果如下:
ParseResult(scheme='止,是scheme。从://开始到一个/位置,是netloc域名。从/开始到;分号为止是path,访问页面的路径。;开始到?为止是params参数。从?问号开始到#井号结束时query查询参数。最后是fragment锚点参数。
5、urlopen()方法
该方法返回的是HTTPResponse对象:
import urllib.request as request response = request.urlopen('www.bigdata17.com') print(response) <www.bigdata17.com') print(response.read().decode('utf-8'))
使用该方法时要注意网站使用的编码格式,配合decode()方法一起使用,否则会出现乱码。像百度用的是utf-8,网易用的是gbk。
getHeaders()方法返回的是网页的头信息:
import urllib.request as request response = request.urlopen('www.bigdata17.com') print(response.getheaders())
结果:
[('Server', 'nginx/1.12.2'), ('Date', 'Mon, 12 Nov 2018 15:45:22 GMT'), ('Content-Type', 'text/html'), ('Content-Length', '38274'), ('Last-Modified', 'Thu, 08 Nov 2018 00:35:52 GMT'), ('Connection', 'close'), ('ETag', '"5be384e8-9582"'), ('Accept-Ranges', 'bytes')]
继续看urlopen()方法有哪些参数:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
其中url是必须传递的参数,其他的参数不是必须传递的。data用于将数据传输到我们要爬取的网站上,例如用户名、密码、验证码等。timeout是设置请求超时时间。
data参数的用法:
>>> import urllib.parse as parse >>> import urllib.request as request >>> data = bytes(parse.urlencode({'username': 'bigdata17'}), encoding='utf8') >>> print(data) b'username=bigdata17' >>> response = request.urlopen('www.bigdata17.com', timeout=1) print(response.read())
如果将timeout设置为0.01,则会报如下的错误:
socket.timeout: timed out
During handling of the above exception, another exception
设置请求头信息:
请求的头信息一般对带有浏览器的信息,很多网站根据请求头信息来判断该请求是正常的浏览器发起的还是由爬虫发起的。设置爬虫头信息方法:
from urllib import request, parse url = 'www.bigdata17.com:3128/'}) proxy_auth_handler = urllib.request.ProxyBasicAuthHandler() proxy_auth_handler.add_password('realm', 'host', 'username', 'password') opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler) # This time, rather than install the OpenerDirector, we use it directly: opener.open('accounts.douban.com/login?alias=&redir=https%3A%2F%2Fwww.douban.com%2F&source=index_nav&error=1001')
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易盾网络的支持。

