urllib库是python内置的http请求库
四个模块
-
urllib.request :请求模块
-
urllib.error: 异常处理模块
-
urllib.parse : url解析模块
工具模块, 提供了很多处理方法:拆分、合并...
-
urllib.robotparser : robots.txt解析模块(用的不是很多)
判断哪些网站是可以爬的那些不可以
关于导包
python2中:
import urllib2
urllib2.urlopen(url)
python3中:
import urllib.request
urllib.request.urlopen(url)
使用
get方式获取数据:
response = urllib.request.urlopen('http://www.baidu.com')
print(response.read())
post方式获取:需要传data参数、headers
将cookie信息存到本地:
import http.cookiejar, urllib.request
cookie = http.cookiejar.MozillaCookieJar('cookie.txt')
# 也可以把Mozilla改成LWP
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)
打开当前路径下的cookie.txt,发现都记录下来了。
将存的cookie读取出来
import http.cookiejar, urllib.request
cookie = http.cookiejar.MozillaCookieJar()
cookie.load('cookie.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'))
这样,在请求网页的时候,会自动把读取出来的cookie传进请求里面, 维持一个登录状态。
异常处理
- e.reason 打印异常原因
try:
response = request.urlopen('http://www.baidu.com')
except error.HTTPError as e:
print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e:
print(e.reason)
else:
print('请求成功')
URL解析(工具模块)
urlparse
from urllib.parse import urlparse
result = urlparse('https://www.baidu.com/home/news/data/newspage?nid=15382671805503563942&n_type=0&p_from=1')
print(type(result),result)
输出结果:
<class 'urllib.parse.ParseResult'>
ParseResult(
scheme='https',
netloc='www.baidu.com', path='/home/news/data/newspage',
params='',
query='nid=15382671805503563942&n_type=0&p_from=1',
fragment=''
)
urlunparse
传入一个数组,自动拼接成url
from urllib.parse import urlunparse
# 注意参数个数
data = ['http', 'www.weibo.com', 'index.html','user', 'a=7','fragment']
print(urlunparse(data))
urljoin 拼接url
urlencode
把一个字典对象,转换成get请求参数
from urllib.parse import urlencode
params = {
'name': 'dimples',
'age': 24
}
base_url = 'http://www.weibo.com?'
url = base_url + urlencode(params)
print(url)