The urllib library provides a series of functions for manipulating URLs.
The request module of urllib makes it very convenient to fetch the content of a URL—this means sending a GET request to a specified page and then returning the HTTP response:
For example, fetch the content of a Douban URL https://api.douban.com/v2/book/2129650 and return the response:
from urllib import request
with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
data = f.read()
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' % (k, v))
print('Data:', data.decode('utf-8'))
You can see the HTTP response headers and JSON data:
Status: 200 OK
Server: nginx
Date: Tue, 26 May 2015 10:02:27 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 2049
Connection: close
Expires: Sun, 1 Jan 2006 01:00:00 GMT
Pragma: no-cache
Cache-Control: must-revalidate, no-cache, private
X-DAE-Node: pidl1
Data: {"rating":{"max":10,"numRaters":16,"average":"7.4","min":0},"subtitle":"","author":["廖雪峰编著"],"pubdate":"2007-6",...}
If we want to simulate a browser sending a GET request, we need to use a Request object. By adding HTTP headers to the Request object, we can disguise the request as coming from a browser. For example, simulate an iPhone to request the Douban homepage:
from urllib import request
req = request.Request('http://www.douban.com/')
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
with request.urlopen(req) as f:
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' % (k, v))
print('Data:', f.read().decode('utf-8'))
In this case, Douban will return a mobile version of the webpage suitable for iPhone:
...
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="format-detection" content="telephone=no">
<link rel="apple-touch-icon" sizes="57x57" href="http://img4.douban.com/pics/cardkit/launcher/57.png" />
...
To send a POST request, you only need to pass the data parameter in bytes format.
Let’s simulate a Weibo login: first read the login email and password, then encode and pass them in the format username=xxx&password=xxx as required by the weibo.cn login page:
from urllib import request, parse
print('Login to weibo.cn...')
email = input('Email: ')
passwd = input('Password: ')
login_data = parse.urlencode([
('username', email),
('password', passwd),
('entry', 'mweibo'),
('client_id', ''),
('savestate', '1'),
('ec', ''),
('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')
])
req = request.Request('https://passport.weibo.cn/sso/login')
req.add_header('Origin', 'https://passport.weibo.cn')
req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')
with request.urlopen(req, data=login_data.encode('utf-8')) as f:
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' % (k, v))
print('Data:', f.read().decode('utf-8'))
If the login is successful, the response we get is as follows:
Status: 200 OK
Server: nginx/1.2.0
...
Set-Cookie: SSOLoginState=1432620126; path=/; domain=weibo.cn
...
Data: {"retcode":20000000,"msg":"","data":{...,"uid":"1658384301"}}
If the login fails, the response we get is as follows:
...
Data: {"retcode":50011015,"msg":"\u7528\u6237\u540d\u6216\u5bc6\u7801\u9519\u8bef","data":{"username":"example@python.org","errline":536}}
For more complex control—such as accessing a website through a proxy—we need to use ProxyHandler for processing. Example code is as follows:
proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
with opener.open('http://www.example.com/login.html') as f:
pass
The functionality provided by urllib is to use programs to execute various HTTP requests. To simulate a browser to complete specific functions, you need to disguise the request as a browser. The way to disguise it is to first monitor the requests sent by the browser, then mimic the browser’s request headers—the User-Agent header is used to identify the browser.
Use urllib to read JSON, then parse the JSON into a Python object:
from urllib import request
def fetch_data(url):
return ''
# Test
URL = 'https://api.weatherapi.com/v1/current.json?key=b4e8f86b44654e6b86885330242207&q=Beijing&aqi=no'
data = fetch_data(URL)
print(data)
assert data['location']['name'] == 'Beijing'
print('ok')
use_urllib.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from urllib import request, parse
# get:
with request.urlopen("https://api.douban.com/v2/book/2129650") as f:
data = f.read()
print("Status:", f.status, f.reason)
for k, v in f.getheaders():
print("%s: %s" % (k, v))
print("Data:", data.decode("utf-8"))
# advanced get:
req = request.Request("http://www.douban.com/")
req.add_header("User-Agent", "Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25")
with request.urlopen(req) as f:
print("Status:", f.status, f.reason)
for k, v in f.getheaders():
print("%s: %s" % (k, v))
print("Data:", f.read().decode("utf-8"))
# post:
print("Login to weibo.cn...")
email = input("Email: ")
passwd = input("Password: ")
login_data = parse.urlencode([("username", email), ("password", passwd), ("entry", "mweibo"), ("client_id", ""), ("savestate", "1"), ("ec", ""), ("pagerefer", "https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F%3Fjumpfrom%3Dweibocom&jumpfrom=weibocom")])
req = request.Request("https://passport.weibo.cn/sso/login")
req.add_header("Origin", "https://passport.weibo.cn")
req.add_header("User-Agent", "Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25")
req.add_header("Referer", "https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F%3Fjumpfrom%3Dweibocom")
with request.urlopen(req, data=login_data.encode("utf-8")) as f:
print("Status:", f.status, f.reason)
for k, v in f.getheaders():
print("%s: %s" % (k, v))
print("Data:", f.read().decode("utf-8"))
# with proxy and proxy auth:
proxy_handler = urllib.request.ProxyHandler({"http": "http://www.example.com:3128/"})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password("realm", "host", "username", "password")
opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
with opener.open("http://www.example.com/login.html") as f:
pass