Urllib是Python内置的HTTP请求库,提供了一系列用于操作URL的函数,包括从网页中获取数据、修改HTTP请求头等。下面是Urllib库的基本使用方法:
- 发送HTTP请求
Urllib库提供了urlopen()函数,可以用于发送HTTP请求并获取响应。以下是一个简单的例子:
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
html = response.read()
print(html)
- 请求头设置
有些网站会根据请求头的不同返回不同的内容,因此在爬虫中设置请求头是非常重要的。Urllib库提供了Request类,可以用于设置请求头。以下是一个例子:
import urllib.request
url = 'http://www.baidu.com'
headers = {
'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'}
req = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(req)
html = response.read()
print(html)
- POST请求
有些网站需要使用POST请求才能获取到数据,Urllib库也提供了相应的函数。以下是一个例子:
import urllib.parse
import urllib.request
url = 'http://www.example.com/login'
data = {'username': 'admin', 'password': '123456'}
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
html = response.read()
print(html)
- 异常处理
在爬虫过程中,可能会遇到各种异常情况,例如网络连接失败、服务器错误等。Urllib库提供了相应的异常类,可以用于处理这些异常。以下是一个例子:
import urllib.request
import urllib.error
try:
response = urllib.request.urlopen('http://www.example.com')
except urllib.error.URLError as e:
if hasattr(e, 'reason'):
print('Failed to reach the server.')
print('Reason:', e.reason)
elif hasattr(e, 'code'):
print('The server could not fulfill the request.')
print('Error code:', e.code)
else:
html = response.read()
print(html)
以上就是Urllib库的基本使用方法,希望对初学者有所帮助。当然,在实际的爬虫项目中,可能需要更加复杂的操作和处理