请求对象的定制
import urllib.request
url=("https://www.baidu.com")
heards = {
'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36'
}
request = urllib.request.Request(url=url,headers=heards)
respose = urllib.request.urlopen(request)
context = respose.read().decode("utf-8")
print(context)
import urllib.request
import urllib.parse
# 定制requset请求方式,并对请求方式进行编码单个参数
# urllib.parse.quote方法
# url = 'https://www.baidu.com/s?wd='
# data = urllib.parse.quote('董宇辉')
#
# base_url = url + data
#
# request = urllib.request.Request(url=base_url,headers=heards)
#
# response = urllib.request.urlopen(request)
# context = response.read().decode("utf-8")
# print(context)
# 定制requset请求 多参数编解码问题,多参数转换unicode
# urllib.parse.urlencode方法
import urllib
import urllib.parse
url = 'https://www.baidu.com/s?'
data = {
'wd': '董宇辉',
'sex': '男',
}
data = urllib.parse.urlencode(data)
new_url = url + data
request = urllib.request.Request(url=new_url,headers=heards)
respose = urllib.request.urlopen(request)
context = respose.read().decode('utf-8')
print(context)
标签:python,基础,request,urllib,parse,url,context,data
From: https://www.cnblogs.com/dhcc/p/18294240