python3 + urllib

Response

from urllib import request

response = request.urlopen("https://www.python.org")

#响应类型
print(type(response))

#响应状态、响应头
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))

#响应体
print(response.read().decode('utf-8'))

 

Request

from urllib import parse
from urllib import request

response = request.urlopen('http://httpbin.org/get')
print(response.read().decode('utf-8'))

data = bytes(parse.urlencode({'name':'张三'}),encoding='utf-8')
response = request.urlopen('http://httpbin.org/post',data=data)
print(response.read().decode('utf-8'))

 

from urllib import parse
from urllib import request

url = 'http://httpbin.org/post'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36'
}
data = {
    'name':'张三'
}
data = bytes(parse.urlencode(data),encoding='utf8')
req = request.Request(url=url,data=data,headers=headers,method='POST')
req.add_header('myhead','myhead_value')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

 Handler

import urllib

proxy_handler = urllib.request.ProxyHandler({
    'http':'http://127.0.0.1:4571',
    'https':'https://127.0.0.1:4571'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open("http://httpbin.org/get")
print(response.read())

Cookie

import http.cookiejar
import urllib
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保存到文件

# 火狐浏览器保存模式
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)

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)

filename = "cookie.txt"
cookie = http.cookiejar.LWPCookieJar(filename)
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'))
View Code

异常处理

from urllib import request,error

try:
    response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:
    print(e.reason)

#结果:Not Found

示例

from urllib import request,error
import socket
try:
    response = request.urlopen('http://cuiqingcai.com/index.htm',timeout=1)
except error.HTTPError as e:
    print(e.reason,e.code,e.headers,sep='\n')
except error.URLError as e:
    print(e.reason)
    if isinstance(e.reason,socket.timeout):
        print("Time Out")
else:
    print("Request Successfully")
View Code

结果

Not Found
404
Server: nginx/1.10.3 (Ubuntu)
Date: Sun, 09 Sep 2018 07:22:35 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
Vary: Cookie
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Link: <https://cuiqingcai.com/wp-json/>; rel="https://api.w.org/"
View Code

 URL解析

urlparse

from urllib.parse import urlparse

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

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

result = urlparse("http://www.baidu.com/index.html#comment",allow_fragments=False)
print(type(result),result)
#result:<class 'urllib.parse.ParseResult'> ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html#comment', params='', query='', fragment='')
View Code

urlunparse

from urllib.parse import urlunparse

data = {'http','www.baidu.com','index.html','user','a=6','comment'}
print(urlunparse(data))
#result: comment://index.html/http;www.baidu.com?user#a=6

urljoin

from urllib.parse import urljoin

print(urljoin("http://www.baidu.com",'index.html'))
print(urljoin("http://www.baidu.com",'?category=2#comment'))
print(urljoin("http://www.baidu.com#comment",'?category=2#comment'))
# http://www.baidu.com/index.html
# http://www.baidu.com?category=2#comment
# http://www.baidu.com?category=2#comment

urlencode

from urllib.parse import urlencode

params = {
    'name':"germey",
    'age':23
}
base_url = "http://www.baidu.com"
url = base_url + urlencode(params)
print(url)

 

posted @ 2018-09-09 14:35  逐梦客!  阅读(141)  评论(0)    收藏  举报