python urllib模块的使用方法
Python中的Urllib模块是一个内置的HTTP客户端库,它支持许多HTTP请求方法,如GET、POST、PUT等,同时也支持Cookie、HTTP和HTTPS代理设置等功能。本文将介绍如何使用Python的Urllib模块。
1. 发送HTTP GET请求
以下代码演示如何使用Urllib库发送HTTP GET请求。
import urllib.request
response = urllib.request.urlopen('https://www.baidu.com')
print(response.read())
以上代码发送了一个GET请求到百度主页,然后打印出响应内容。
2. 发送HTTP POST请求
以下代码演示如何使用Urllib库发送HTTP POST请求。
import urllib.parse
import urllib.request
url = 'https://www.baidu.com/s'
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
values = {'wd': 'urllib'}
headers = {'User-Agent': user_agent}
data = urllib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
print(response.read())
以上代码发送了一个POST请求到百度搜索页面,然后打印出响应内容。代码首先使用urllib.parse.urlencode()方法将请求数据转换成urlencode编码的字符串,然后使用encode方法将字符串转换成字节流,最后使用urllib.request.Request()方法创建请求对象,其中传入请求URL、请求数据和请求头。发送请求和获取响应的方法与使用GET请求的方法相同。
3. 设置请求头
以下代码演示如何使用Urllib设置HTTP请求头。
import urllib.request
url = 'http://python.org/'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'}
req = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(req)
print(response.status)
以上代码设置了HTTP请求头中的User-Agent字段,使用urllib.request.Request()方法创建请求对象时,将请求头放入headers参数中。
4. 处理Cookie
以下代码演示如何使用Urllib处理Cookie。
import http.cookiejar
import 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('Name = %s' % item.name)
print('Value = %s' % item.value)
以上代码使用http.cookiejar模块创建了一个CookieJar对象,然后将它传入urllib.request.HTTPCookieProcessor()方法创建处理器对象,使用urllib.request.build_opener()方法创建Opener对象,使用它发送请求并获取响应。处理Cookie的过程完全由CookieJar和HTTPCookieProcessor处理器负责。
5. 使用代理
以下代码演示如何使用Urllib设置代理。
import urllib.request
proxy_handler = urllib.request.ProxyHandler({'http': 'http://localhost:8888'})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('http://www.baidu.com')
print(response.read())
以上代码使用urllib.request.ProxyHandler()方法创建代理处理器对象,将其传入urllib.request.build_opener()方法创建Opener对象,并使用它发送请求。其中,代理地址为http://localhost:8888。这个代理地址需要修改为你自己的代理地址。
6. 处理异常
以下代码演示如何使用Urllib处理HTTP请求中的异常。
import urllib.request
try:
response = urllib.request.urlopen('http://python.org')
except urllib.error.URLError as e:
print(e.reason)
以上代码使用urllib.request.urlopen()方法发送HTTP请求,如果出现异常,则使用urllib.error.URLError对象和其属性e.reason获取异常信息。
总结:
以上就是Python中Urllib库的常用方法,包括发送HTTP请求、处理Cookie、使用代理、设置请求头等。我们可以根据实际需求使用这些方法来完成不同的应用需求。
