urllib中的get请求

下面为python3中的urllib库对于get请求的使用方法,接口的地方需要拼接地址,以访问百度为例,附上代码:

import urllib
from urllib import request
from urllib import parse     #导入编码  解码

headers={"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36"}

url="https://www.baidu.com/s?"   #百度链接
word={"wd":"关晓彤"}     #百度关键词接口
word=parse.urlencode(word)   #编码成字符串
newurl=url+word       # 拼接网址

request=urllib.request.Request(newurl,headers=headers)   #发送请求
response=urllib.request.urlopen(request)   ##打开请求
print(response.code)     #打印请求状态码
html=response.read().decode("utf-8")  #读取页面数据  并进行utf-8解码

print(html)

 

原文地址:https://www.cnblogs.com/my-global/p/12441133.html