python—urllib库的使用

Urllib库

"""
python 内置的HTTP请求库
urllib.request 请求模块
urllib.error 异常处理模块
urllib.parse url解析模块
urllib.robotparser  robots.txt 解析模块
"""

# python2
import urllib2
response = urllib2.urlopen('http://www.baidu.com')
# python3
import urllib.request
resp = urllib.request.urlopen('http://www.baidu.com')

urllib的请求

# get 请求
import urllib.request
resp = urllib.request.urlopen('http://www.baidu.com')
print(resp.read().decode("utf-8"))

# post请求
import urllib.parse
import urllib.request
#http://httpbin.org/get  测试http请求
data = bytes(urllib.parse.urlencode({"world":"hello"}),encoding="utf8")
response = urllib.request.urlopen("http://httpbin.org/get",data=data)
print(response.read())

# 设置超时等待时间
import urllib.request
resp = urllib.request.urlopen('http://httpbin.org/get',timeout=1)
print(resp.read().decode("utf-8"))

# 异常处理
import socket
import urllib.request
import urllib.error

try:
	resp = 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")

urllib 响应

# 状态码和响应头
import urllib.request
resp = urllib.request.urlopen('http://httpbin.org/get',timeout=1)
print(resp.status)
print(resp.getheaders())
# 一个列表,列表里面是一个一个的2位元祖[("server","nginx"),]
print(resp.getheader("server")) # nginx

# 响应体的内容
print(response.read()decode("utf8"))

更为复杂的请求

# 使用urllib.request 创造一个对象,传入urlopen
import urllib.request

request = urllib.request.Request('https://python.org')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))


# 增加请求头和数据
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'))

# 另外增加请求头的方法
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, 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'))

设置代理

import urllib.request

proxy_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())

cookie

# 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)
    
# 存cookie,保存到本地txt,MozillaCookieJar格式
import http.cookiejar, urllib.request
filename = "cookie.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)

# LWPCookieJar格式保存cookie
import http.cookiejar, urllib.request
filename = '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)

# 读取刚刚保存下来的cookie
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'))

异常处理

# 打印异常信息
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, error

try:
    response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e: #httperror 有三个属性
    print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e: #URLErrot 有一个属性
    print(e.reason)
else:
    print('Request Successfully')

# 异常原因
import socket
import urllib.request
import urllib.error

try:
    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')

urlparse

# 传入url,将url分割
urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
# url 拆分为标准结构,我们可以去取自己想要的片段
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result)
"""
<class 'urllib.parse.ParseResult'> 
ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')

协议类型  域名 地址  
params='user'这个不常用到, 
query='id=5'

fragment='comment'
#fragment: 片段ID
该部分与上面的?后面的表单信息本质的区别就是这部分内容不会被传递到服务器端。一般用于页面的锚。就是我们常见的网站右下脚一般有一个回到顶部的按钮,一般就是使用其实现的。
"""
# 指定协议类型
from urllib.parse import urlparse

result = urlparse('www.baidu.com/index.html;user?id=5#comment', scheme='https')
print(result)

# 如果已经指定了,后面的https不会生效
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', scheme='https')
print(result)
# allow_fragments=False,#comment会向前拼接
from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', allow_fragments=False)
print(result)

from urllib.parse import urlparse

result = urlparse('http://www.baidu.com/index.html#comment', allow_fragments=False)
print(result)

urlunparse

"""
与 urlparse是反函数
urlparse是拆分,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

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/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
"""

urlencode

# 将字典转换成url参数
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

猜你喜欢

转载自blog.csdn.net/sunt2018/article/details/85875339