请求库urllib使用

请求方法request

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

编码parse中的quote方式

import urllib.requestimport 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.requestimport 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())

POST请求

Ajax请求

抓取百度翻译结果

# post请求# 抓取百度翻译的翻译结果# 百度翻译基于Ajax发起的请求import urllib.requestimport urllib.parseimport json# 用户输入要翻译的关键字choice = input("请输入您要翻译的关键字>>>:").strip()# 在网页中用开发者工具找到Ajax请求的真实网址url = "https://fanyi.baidu.com/sug"# 构建请求参数data = { ‘kw‘:choice,}# 对参数进行编码处理,返回值为str,kw=%E5%93%88data = urllib.parse.urlencode(data)# 将编码后的结果转换成bytes类型data = data.encode()# 发起post请求,经过处理后的data就是post请求携带的参数,返回值为bytes类型response = urllib.request.urlopen(url=url,data=data)# 将bytes解码json.loads(response.read())

相关文章