请求库urllib使用

Posted youxiu123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了请求库urllib使用相关的知识,希望对你有一定的参考价值。

请求方法request

技术图片
import urllib.request
url = "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.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())
技术图片

POST请求

Ajax请求

抓取百度翻译结果

技术图片
# post请求
# 抓取百度翻译的翻译结果
# 百度翻译基于Ajax发起的请求
import urllib.request
import urllib.parse
import json
# 用户输入要翻译的关键字
choice = input("请输入您要翻译的关键字>>>:").strip()
# 在网页中用开发者工具找到Ajax请求的真实网址
url = "https://fanyi.baidu.com/sug"
# 构建请求参数
data = 
    ‘kw‘:choice,

# 对参数进行编码处理,返回值为str,kw=%E5%93%88
data = 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())
技术图片

以上是关于请求库urllib使用的主要内容,如果未能解决你的问题,请参考以下文章

Python爬虫技术栈 | urllib库&&urllib3库

Python爬虫技术栈 | urllib库&&urllib3库

Python爬虫技术栈 | urllib库&&urllib3库

urllib库

Urllib库的使用

《爬虫学习》(urllib库使用)