1.urllib 库
安装命令:
pip install urllib
urllib :Python内置的HTTP请求库
# Python2
import urllib2
response = urllib2.urlopen('http://www.baidu.com')# Python3
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
(1)urllib.request:请求模
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
1)url:请求的 url 地址
import urllib.requestresponse = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))
2)data:发送请求是提交的必要数据
后面的暂时不用!!!
import urllib.parse
import urllib.requestdata = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())
3)timeout:超时设置
import urllib.request# timeout=1 在1秒内没有获取到响应,则抛出异常
response = urllib.request.urlopen('http://httpbin.org/get', timeout=1)
print(response.read())# ---------------------------------------------------------------------import socket
import urllib.request
import urllib.errortry: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')
post请求:
from urllib import request, parseurl = 'http://httpbin.org/post'
dict = {'name': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, method='POST')
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
response = request.urlopen(req)
print(response.read().decode('utf-8'))
添加headers的方法:
from urllib import request, parseurl = 'http://httpbin.org/post'
dict = {'name': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, method='POST')
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
response = request.urlopen(req)
print(response.read().decode('utf-8'))
响应
获取响应类型:type(response)
import urllib.requestresponse = urllib.request.urlopen('https://www.python.org')
print(type(response))# <class 'http.client.HTTPResponse'>
状态码、响应头
获取状态码:response.status
获取响应头:response.getheaders()
获取响应头指定内容: response.getheaders('Server')
import urllib.requestresponse = urllib.request.urlopen('https://www.python.org')
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))#
200
[('Server', 'nginx'), ('Content-Type', 'text/html; charset=utf-8'), ('X-Frame-Options', 'SAMEORIGIN'), ('X-Clacks-Overhead', 'GNU Terry Pratchett'), ('Content-Length', '47436'), ('Accept-Ranges', 'bytes'), ('Date', 'Wed, 22 Mar 2017 15:40:16 GMT'), ('Via', '1.1 varnish'), ('Age', '3417'), ('Connection', 'close'), ('X-Served-By', 'cache-itm7426-ITM'), ('X-Cache', 'HIT'), ('X-Cache-Hits', '16'), ('X-Timer', 'S1490197216.605863,VS0,VE0'), ('Vary', 'Cookie'), ('Public-Key-Pins', 'max-age=600; includeSubDomains; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="5C8kvU039KouVrl52D0eZSGf4Onjo4Khs8tmyTlV3nU="; pin-sha256="5C8kvU039KouVrl52D0eZSGf4Onjo4Khs8tmyTlV3nU="; pin-sha256="lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU="; pin-sha256="TUDnr0MEoJ3of7+YliBMBVFB4/gJsv5zO7IxD9+YoWI="; pin-sha256="x4QzPSC810K5/cMjb05Qm4k3Bw5zBn4lTdO/nEW/Td4=";'), ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]
nginx
(2)urllib.error:异常处理模块
from urllib import request, error
try:response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:print(e.reason)# -----------------------------------------------------------------from urllib import request, errortry: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')# -----------------------------------------------------------------import socket
import urllib.request
import urllib.errortry:response = urllib.request.urlopen('https://www.baidu.com', timeout=0.01)
except urllib.error.URLError as e:print(type(e.reason))if isinstance(e.reason, socket.timeout):print('TIME OUT')
(3)urllib.parse:url解析模块
urlparse: urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
urlstring: 请求 url 地址
scheme: 协议类型(可以是 http https)
from urllib.parse import urlparseresult = urlparse('http://www.baidu.com/index.html;user?id=5#comment', scheme='https')
print(result)ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')# -----------------------------------------------from urllib.parse import urlparseresult = urlparse('http://www.baidu.com/index.html;user?id=5#comment', allow_fragments=False)
print(result)ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5#comment', fragment='')
urlunparse: url拼接
from urllib.parse import urlunparsedata = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']
print(urlunparse(data))# http://www.baidu.com/index.html;user?a=6#comment
urljoin url 合并:
from urllib.parse import urljoinprint(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'))'''
result:
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
'''
urlencode: 字典转换为 url 参数:
from urllib.parse import urlencodeparams = {'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
(4)urllib.robotparser:robots.txt解析模块
(5)代理 Handler
import urllib.requestproxy_handler = urllib.request.ProxyHandler({'http': 'http://127.0.0.1:9743','https': 'https://127.0.0.1:9743'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('http://httpbin.org/get')
print(response.read())
(6)Cookie
import http.cookiejar, urllib.requestcookie = 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)# -------------------------------------------------------import http.cookiejar, urllib.request
cookie = http.cookiejar.LWPCookieJar()
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'))