urllib 库的基本使用
1.url.request(get)
import urllib.request response = urllib.request.urlopen('http://www.baidu.com') print(response.read().decode('utf-8'))
2.url.request (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())
3.url.request(超时正确)
import urllib.request response = urllib.request.urlopen('http://httpbin.org/get',timeout=1) print(response.read())
4.url.request(超时错误)
import urllib.request import socket 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')
5.状态头,响应码
import urllib.request response = urllib.request.urlopen('http://www.python.org') print(type(response)) print(response.status) print(response.getheaders()) print(response.getheader('Server'))
6.Request
import urllib.request request = urllib.request.Request('http://www.baidu.com') response=urllib.request.urlopen(request) print(response.read().decode('utf-8'))
6.1.参数的使用
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='utf-8') req = request.Request(url=url,data=data,headers=headers,method='POST') response = request.urlopen(req) print(response.read().decode('utf-8'))
6.2.追加的方法
from urllib import request,parse url = 'http://httpbin.org/post' dict = { 'name':'Germey', } data = bytes(parse.urlencode(dict),encoding='utf8') req = request.Request(url=url,data=data,headers=headers,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'))
handler
7. 代理
import urllib.request proxy_handler = urllib.request.ProxyHandler({ 'http':'http://localhost:9743', 'https':'https://localhost:9743' }) opener = urllib.request.build_opener(proxy_handler) response = opener.open('http://www.baidu.com') print(response.read())
8.Cookie
import http.cookiejar,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)
8.1.Cookie保存到本地
方式一:
import http.cookiejar,urllib.request filename = "coookie.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)
方式二:
import http.cookiejar,urllib.request filename = "coookie1.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)
8.2.读取cookie 文件
(1) from urllib import request,error try: response = request.urlopen('http://cuiqingcai.com/index.html') except error.URLError as e: print(e.reason) (2) 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 Sucessfully')
9.URL解析:
(1) from urllib.parse import urlparse result = urlparse('http://www.baidu.com/index.html;user?id=5#comment') print(type(result),result) (2) from urllib.parse import urlparse result = urlparse('www.baidu.com/index.html;user?id=5#comment',scheme='https') print(result) (3) from urllib.parse import urlparse result = urlparse('http://www.baidu.com/index.html;user?id=5#comment',scheme='https') print(result) (4) from urllib.parse import urlparse result = urlparse('http://www.baidu.com/index.html;user?id=5#comment',allow_fragments=False) print(result) (5) from urllib.parse import urlparse result = urlparse('http://www.baidu.com/index.html#comment',allow_fragments=False) print(result)
10.urlunparse:(url参数拼接)
from urllib.parse import urlunparse data=['http','www.baidu.com','index.html','user','a=6','comment'] print(urlunparse(data))
11.urljoin:(url追加,后者如果完整会覆盖掉前者,如果不完整就拼接)
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','https://cuiqingcai.com/FAQ.html?question=2')) print(urljoin('http://www.baidu.com','https://cuiqingcai.com/index.php')) print(urljoin('http://www.baidu.com?wd=abc','https://cuiqing.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'))
这里由于运行结果太多,有的直接就是html代码就不展示运行结果了。希望对初学者有所帮助。