怎样建设的网站好优化好排名,商城网站设计实训总结,wdcp wordpress 502,嘉兴电子商务网站建设文章目录 1、urllib介绍2、urllib的基本方法介绍2.1 urllib.Request2.2 response.read() 3、urllib请求百度首页的完整例子4、小结 1、urllib介绍
除了requests模块可以发送请求之外, urllib模块也可以实现请求的发送,只是操作方法略有不同!
urllib在python中分为urllib和url… 文章目录 1、urllib介绍2、urllib的基本方法介绍2.1 urllib.Request2.2 response.read() 3、urllib请求百度首页的完整例子4、小结 1、urllib介绍
除了requests模块可以发送请求之外, urllib模块也可以实现请求的发送,只是操作方法略有不同!
urllib在python中分为urllib和urllib2在python3中为urllib
下面以python3的urllib为例进行讲解
2、urllib的基本方法介绍
2.1 urllib.Request 构造简单请求 import urllib
#构造请求
request urllib.request.Request(http://www.baidu.com)
#发送请求获取响应
response urllib.request.urlopen(request)传入headers参数 import urllib
#构造headers
headers {User-Agent : Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)}
#构造请求
request urllib.request.Request(url, headers headers)
#发送请求
response urllib.request.urlopen(request)传入data参数 实现发送post请求示例 import urllib.request
import urllib.parse
import jsonurl http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?opkeyword
headers {User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Safari/605.1.15,}
data {cname: ,pid: ,keyword: 北京,pageIndex: 1,pageSize: 10,
}
# 使用post方式
# 需要
data urllib.parse.urlencode(data).encode(utf-8)
req urllib.request.Request(url, datadata, headersheaders)
res urllib.request.urlopen(req)
print(res.getcode())
print(res.geturl())
data json.loads(res.read().decode(utf-8))
# print(data)
for i in data[Table1]:print(i)2.2 response.read()
获取响应的html字符串,bytes类型
#发送请求
response urllib.request.urlopen(http://www.baidu.com)
#获取响应
response.read()3、urllib请求百度首页的完整例子
import urllib.requestimport json
url http://www.baidu.com
#构造headers
headers {User-Agent : Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)}
#构造请求
request urllib.request.Request(url, headers headers)
#发送请求
response urllib.request.urlopen(request)
#获取html字符串
html_str response.read().decode(utf-8)
print(html_str)4、小结
urllib.request中实现了构造请求和发送请求的方法urllib.request.Request(url,headers,data)能够构造请求urllib.request.urlopen能够接受request请求或者url地址发送请求获取响应response.read()能够实现获取响应中的bytes字符串