urllib2模块:Python网络编程利器
发布时间:2024-01-08 03:34:14
urllib2是Python的一个内置模块,它提供了一个简单而强大的接口来处理网络请求。在Python 3中,urllib2已经重命名为urllib.request,但其功能和用法基本相同。
使用urllib2,我们可以实现如下功能:
- 发送GET/POST请求
- 获取网页内容
- 设置请求头信息
- 处理cookie
- 进行HTTP认证
- 处理重定向
- 设置代理服务器
下面是一个使用urllib2发送GET请求获取网页内容的例子:
import urllib2
def get_html(url):
try:
response = urllib2.urlopen(url)
html = response.read()
return html
except urllib2.URLError as e:
print "Error: ", e.reason
url = "http://www.example.com"
html = get_html(url)
print html
在例子中,我们定义了一个get_html函数,接受一个url参数。通过urllib2.urlopen(url)发送GET请求,返回一个响应对象response,然后使用response.read()方法获取网页内容。
此外,还可以设置请求头信息,以模拟浏览器发送HTTP请求,例如:
import urllib2
def get_html(url):
try:
req = urllib2.Request(url, headers={'User-Agent' : 'Mozilla/5.0'})
response = urllib2.urlopen(req)
html = response.read()
return html
except urllib2.URLError as e:
print "Error: ", e.reason
url = "http://www.example.com"
html = get_html(url)
print html
在这个例子中,我们使用urllib2.Request()创建一个请求对象req,其中包含一个自定义的User-Agent头信息,然后使用urllib2.urlopen(req)发送请求。
另外,还可以使用urllib2来发送POST请求,方法类似,只需将请求改为POST并将参数以data参数传递,例如:
import urllib2
import urllib
def post_data(url, data):
try:
req = urllib2.Request(url, data=urllib.urlencode(data))
response = urllib2.urlopen(req)
html = response.read()
return html
except urllib2.URLError as e:
print "Error: ", e.reason
url = "http://www.example.com"
data = {'username': 'bob', 'password': '123456'}
html = post_data(url, data)
print html
在这个例子中,我们使用urllib.urlencode()将字典形式的参数data编码为URL字符串,并将其作为data参数传递给urllib2.Request()。
以上是urllib2模块的基本使用方法和几个常见功能的示例。通过深入学习和理解urllib2的使用文档,我们可以利用urllib2进行各种网络编程任务。
