urllib

请求方法 request

import urllib.request
url = "" #请求的地址
# 打开网页,读取所有内容,注意read出来的是bytes类型的数据
respons = request.urlopen(url=url).read()
# 数据持久化,将读取出来的数据保存在本地
with open("./jiang.html","wb") as fp:
    fp.write(respons)
    print("数据下载成功")

编码parse中的quote方式

import urllib.request
import urllib.parse
# 用户输入搜索的关键字
choice = input("请输入您要查询的关键字>>>:").strip()
# 对关键字进行编码,url不可以出现非ASCII编码的字符数据
Keyword = urllib.parse.quote(choice)
# 将编码后的搜索条件拼接到url上
url = "http://www.baidu.com/s?wd={}".format(Keyword)
# 请求网址
response = urllib.request.urlopen(url=url)
# read取出相应数据,读取出来的是bytes类型的数据
html = response.read()
# 数据持久化,保存到本地
with open("./关键字搜索.html","wb")as fp:
    fp.write(html)
    print("下载完成")

UA伪装

import urllib.request
import urllib.parse
# 用户输入搜索的关键字
choice = input("请输入您要查询的关键字>>>:").strip()
# 对关键字进行编码,url不可以出现非ASCII编码的字符数据
Keyword = urllib.parse.quote(choice)
# 将编码后的搜索条件拼接到url上
url = "https://www.baidu.com/s?wd={}".format(Keyword)
# 伪装浏览器
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}
# 自定制请求对象,加入请求头
request_obj = urllib.request.Request(url=url,headers=header)
# 对我们自定制的请求对象发起请求
response = urllib.request.urlopen(request_obj)
# read取出相应数据,读取出来的是bytes类型的数据
print(response.read())
原文地址:https://www.cnblogs.com/yongyuandishen/p/14904708.html