在Python中,urllib和urllib2库是用于处理URL的标准库,可以用来发送HTTP请求、处理响应、处理URL编码等。不过需要注意的是,在Python 3中,urllib和urllib2已经合并为urllib库。以下是它们的基本用法:
使用urllib库发送HTTP请求:
import urllib.request
#发送GET请求
response=urllib.request.urlopen('www.example.com')
html=response.read()
print(html)
#发送POST请求
data=urllib.parse.urlencode({'key':'value'}).encode('utf-8')
response=urllib.request.urlopen('www.example.com',data=data)
html=response.read()
print(html)
使用urllib库处理URL编码:
import urllib.parse
#编码
params={'param1':'value1','param2':'value2'}
encoded_params=urllib.parse.urlencode(params)
print(encoded_params)
#解码
decoded_params=urllib.parse.parse_qs(encoded_params)
print(decoded_params)
使用urllib.request模块设置请求头:
import urllib.request
url='www.example.com'
req=urllib.request.Request(url,headers={'User-Agent':'Mozilla/5.0'})
response=urllib.request.urlopen(req)
html=response.read()
print(html)
在Python 2中,urllib和urllib2库的用法类似,但有一些细微的差别。以下是在Python 2中使用urllib2库的示例:
import urllib2
#发送GET请求
response=urllib2.urlopen('www.example.com')
html=response.read()
print(html)
#发送POST请求
data=urllib.urlencode({'key':'value'})
request=urllib2.Request('www.example.com',data)
response=urllib2.urlopen(request)
html=response.read()
print(html)
以上是urllib和urllib2库的基本用法,它们是Python中处理URL和发送HTTP请求的重要工具,可以帮助你实现网络数据的获取和处理。