Python官网:该模块定义了有助于在复杂世界中打开 URL(主要是 HTTP)的函数和类——基本和摘要身份验证、重定向、cookie 等等
我们可以用python自带的urllib库中的request模块来完成简单的爬取单个网页
- 通过模拟浏览器构建一个基本Get请求来爬取
import urllib.request
url = 'https://httpbin.org/post'
reponse = urllib.request.urlopen(url)
#用urlopen方法打开url
#response 是 HTTPResposne 类型的对象
print( response.read().decode('utf-8') )
#以utf-8编码方式解码读取返回网页的内容,并打印出来
https://httpbin.org 网站可以提供 HTTP 请求测试
- 通过模拟浏览器构建一个基本Post请求来爬取
import urllib.request,parse
url = 'https://httpbin.org/Post'
dict = {'name':'liu'}
str = urllib.parse.urlencode(dic)
# 将字典dict序列化为 GET 请求参数并返回
#GET请求参数就是URL ?后面的 赋值语句
例如:checkout = 1 & Id=1
data = bytes(str,encoding='utf-8')
# 按照encoding的值来将str转码成字节流对象并返回
try:
reponse = urllib.request.urlopen(url,data = data,timeout = 2)
# 传递data给data参数(必须是bytes类型)并设置超时时间为2秒
# 超过2秒抛出 TimeoutError 异常
#一旦传递了data参数,这变成了一个Post请求
print( response.read().decode('utf-8') )
except urllib.error.URLError as e:
if isinstance(e.reason, socket.timeout):
print('TIME OUT')
- 利用Request类灵活构建请求来爬取
import urllib.request
url = 'https://httpbin.org/post'
#请求头
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Host': 'httpbin.org'
}
dict = {'name':'liu'}
str = urllib.parse.urlencode(dic)
data = bytes(str,encoding='utf-8')
#用url,data(必须是bytes类型),headers,POST实参构造Request对象
request = urllib.request.Request(url,data=data, headers=headers, method='POST')
response = urllib.request.urlopen(request)
#这里urlopen参数要么是url,要么是Request类型对象
print( response.read().decode('utf-8') )



