Urllib库基本使用
1 模块
- urllib.request—————— 请求模块
- urllib.error ——————— 异常处理模块
- urllib.parse——————— url解析模块
- urllib.robotparser———— robots.txt解析模块
2 urlopen
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
2.1 Get请求
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))
2.2 Post请求
import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read().decode('utf-8'))
2.3 超时设置
import socket
import urllib.request
import urllib.error
try:
response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
except urllib.error.URLError as e:
if isinstance(e.reason, socket.timeout):
print('TIME OUT')
- response.read()类型是byte
- response.read().decode(‘utf-8’) 类型是 str
3 响应的属性/方法
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))
response.read() #类型是byte
response.read().decode('utf-8') #类型是str
4 Request
4.1 Get请求
import urllib.request
request = urllib.request.Request('http://www.httpbin.org/get')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
4.2 Post请求
from urllib import request, parse
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 = request.Request(url=url, data=data, headers=headers, method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))
4.3 添加请求头
import urllib.request
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Host': 'httpbin.org'
}
request = urllib.request.Request('http://www.httpbin.org/get',headers=headers)
# request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
5 代理IP
import urllib.request
proxy_handler = urllib.request.ProxyHandler({
'http': 'https://182.34.20.72:808',
'https': 'http://182.34.20.72:808'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('http://httpbin.org/get')
print(response.read().decode('utf-8'))
6 Cookie
6.1 获取Cookie
import http.cookiejar
import urllib.request
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)
6.2 保存Cookie
import http.cookiejar
import urllib.request
cookie = http.cookiejar.MozillaCookieJar("cookie.txt")
# cookie = http.cookiejar.LWPCookieJar(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)
6.3 读取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'))
7 异常处理
from urllib import request, error
try:
response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:
print(e.reason)
8 urlparse
result = urllib.parse.urlparse('http://www.baidu.com/index.html;user?id=5#comment')
ParseResult(scheme=’http’, netloc=’www.baidu.com’, path=’/index.html’, params=’user’, query=’id=5’, fragment=’comment’)
result = urllib.parse.urlparse('www.baidu.com/index.html;user?id=5#comment', scheme='https')
ParseResult(scheme=’https’, netloc=”, path=’www.baidu.com/index.html’, params=’user’, query=’id=5’, fragment=’comment’)
result = urllib.parse.urlparse(‘http://www.baidu.com/index.html;user?id=5#comment‘, scheme=’https’)
ParseResult(scheme=’http’, netloc=’www.baidu.com’, path=’/index.html’, params=’user’, query=’id=5’, fragment=’comment’)
result = urllib.parse.urlparse('http://www.baidu.com/index.html;user?id=5#comment', allow_fragments=False)
ParseResult(scheme=’http’, netloc=’www.baidu.com’, path=’/index.html’, params=’user’, query=’id=5#comment’, fragment=”)
result = urllib.parse.urlparse('http://www.baidu.com/index.html#comment', allow_fragments=False)
ParseResult(scheme=’http’, netloc=’www.baidu.com’, path=’/index.html#comment’, params=”, query=”, fragment=”)
9 urlunparse
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
10 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
11 urlencode
例1
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
例2
import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read().decode('utf-8'))