-
2021-08-12 09:25:29更多相关内容
-
Python使用requests提交HTTP表单的方法
2020-12-23 23:09:27Python的requests库, 其口号是...import requests url = 'www.test.org' data = {'username': 'user', 'password': '123456'} response = requests.post(url, data) 有cookie——显示添加cookie import reques -
python3的 requests离线安装包(包括依赖)
2020-08-14 10:06:15python3的 requests离线安装包,仅window环境能用,离线安装方法如下: 解压到任意目录后,cd到requests目录 然后 pip install --no-index --find-links=pack -r requirements.txt 或者 python -m pip install --no-... -
Python_Requests使用.pdf
2019-12-27 10:45:17Python_Requests使用, Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库,Requests它会比url lib更加方便,urlLib库可以处理客户端的请求和服务器端的请求,还可以解析URL地址 ... -
python requests模块及依赖包.zip
2020-06-24 14:24:15python requests模块的安装包,以及requests所需的依赖包certifi、chardet等等 -
Python3+Requests+Excel完整接口自动化测试框架的实现
2020-12-26 11:55:53框架整体使用Python3+Requests+Excel:包含对实时token的获取 1、——base ——-runmethond.py runmethond:对不同的请求方式进行封装 import json import requests requests.packages.urllib3.disable_warnings() ... -
Python - Requests实现短信验证码注册登录完整示例:Python - Requests.py和附件说明.rar
2020-11-10 10:41:17Python - Requests实现短信验证码注册登录完整示例:Python - Requests.py和附件说明.rar -
Go-Requests-Go一个类似于PythonRequests的Go语言HTTP请求库
2019-08-13 22:40:01Requests-Go,一个类似于 Python Requests 的 Go 语言 HTTP 请求库 -
requests 库中文文档电子书
2018-09-12 21:44:58python ,requests,爬虫框架,适合人类的爬虫框架,适合新手入门,也适合用来随时查询APi -
python requests官方中文文档( 高级用法 Requests 2.18.1 文档 )
2018-08-13 23:24:55python requests官方中文文档,进阶用法。本文档覆盖了requests库的一些高级特性 -
requests 安装包
2016-11-17 14:25:17requests安装包 -
requests库官方文档
2018-10-19 18:20:42requests 2.19.1库最新版官方文档使用教程(原版)。 -
Python爬虫常用库requests、beautifulsoup、selenium、xpath总结
2021-06-24 14:10:57文章目录requestsrequests基础requests模块发送get请求response响应对象response.text 和response.content的区别解决中文乱码response响应对象的其它常用属性或方法requests实操requests模块发送请求发送带参数的...Python爬虫常用库总结:requests、beautifulsoup、selenium、xpath总结
记得安装快速第三方库,Python经常需要安装第三方库,原始的下载速度很慢,使用国内的镜像就很快啦
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple 包名
官方网址:
requests
requests官方文档 https://docs.python-requests.org/zh_CN/latest/
进行爬虫,首先要对网址进行请求,这个时候就要用刀我们的requests模块了。requests是python的一个HTTP客户端库,跟urllib,urllib2类似。与urllib,urllib2相比,requests模块语法更加简单。正如他的官网所说:
requests模块介绍
发送http请求,获取响应数据
requests模块是一个第三方模块,需要在你的python(虚拟)环境中额外安装
pip/pip3 install requests
requests基础
requests模块发送get请求
#https://beishan.blog.csdn.net/ import requests # 目标url url = 'https://www.baidu.com' # 向目标url发送get请求 response = requests.get(url) # 打印响应内容 print(response.text)
response响应对象
观察上边代码运行结果发现,有好多乱码;这是因为编解码使用的字符集不同早造成的;我们尝试使用下边的办法来解决中文乱码问题
import requests url = 'https://www.baidu.com' # 向目标url发送get请求 response = requests.get(url) # 打印响应内容 # print(response.text) print(response.content.decode()) # 注意这里!
- response.text是requests模块按照chardet模块推测出的编码字符集进行解码的结果
- 网络传输的字符串都是bytes类型的,所以response.text = response.content.decode(‘推测出的编码字符集’)
- 我们可以在网页源码中搜索
charset
,尝试参考该编码字符集,注意存在不准确的情况
response.text 和response.content的区别
- response.text
- 类型:str
- 解码类型: requests模块自动根据HTTP 头部对响应的编码作出有根据的推测,推测的文本编码
- response.content
- 类型:bytes
- 解码类型: 没有指定
解决中文乱码
通过对response.content进行decode,来解决中文乱码
response.content.decode()
默认utf-8response.content.decode("GBK")
- 常见的编码字符集
- utf-8
- gbk
- gb2312
- ascii (读音:阿斯克码)
- iso-8859-1
response响应对象的其它常用属性或方法
#https://beishan.blog.csdn.net/ # 1.2.3-response其它常用属性 import requests # 目标url url = 'https://www.baidu.com' # 向目标url发送get请求 response = requests.get(url) # 打印响应内容 # print(response.text) # print(response.content.decode()) # 注意这里! print(response.url) # 打印响应的url print(response.status_code) # 打印响应的状态码 print(response.request.headers) # 打印响应对象的请求头 print(response.headers) # 打印响应头 print(response.request._cookies) # 打印请求携带的cookies print(response.cookies) # 打印响应中携带的cookies
requests实操
requests模块发送请求
发送带header的请求
我们先写一个获取百度首页的代码
import requests url = 'https://www.baidu.com' response = requests.get(url) print(response.content.decode()) # 打印响应对应请求的请求头信息 print(response.request.headers)
从浏览器中复制User-Agent,构造headers字典;完成下面的代码后,运行代码查看结果
import requests url = 'https://www.baidu.com' headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"} # 在请求头中带上User-Agent,模拟浏览器发送请求 response = requests.get(url, headers=headers) print(response.content) # 打印请求头信息 print(response.request.headers)
发送带参数的请求
我们在使用百度搜索的时候经常发现url地址中会有一个
?
,那么该问号后边的就是请求参数,又叫做查询字符串在url携带参数,直接对含有参数的url发起请求
import requests headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"} url = 'https://www.baidu.com/s?wd=python' response = requests.get(url, headers=headers)
通过params携带参数字典
1.构建请求参数字典
2.向接口发送请求的时候带上参数字典,参数字典设置给params
import requests headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"} # 这是目标url # url = 'https://www.baidu.com/s?wd=python' # 最后有没有问号结果都一样 url = 'https://www.baidu.com/s?' # 请求参数是一个字典 即wd=python kw = {'wd': 'python'} # 带上请求参数发起请求,获取响应 response = requests.get(url, headers=headers, params=kw) print(response.content)
- 从浏览器中复制User-Agent和Cookie
- 浏览器中的请求头字段和值与headers参数中必须一致
- headers请求参数字典中的Cookie键对应的值是字符串
import requests url = 'https://github.com/USER_NAME' # 构造请求头字典 headers = { # 从浏览器中复制过来的User-Agent 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36', # 从浏览器中复制过来的Cookie 'Cookie': 'xxx这里是复制过来的cookie字符串' } # 请求头参数字典中携带cookie字符串 resp = requests.get(url, headers=headers) print(resp.text)
超时参数timeout的使用
在平时网上冲浪的过程中,我们经常会遇到网络波动,这个时候,一个请求等了很久可能任然没有结果。
在爬虫中,一个请求很久没有结果,就会让整个项目的效率变得非常低,这个时候我们就需要对请求进行强制要求,让他必须在特定的时间内返回结果,否则就报错。
-
超时参数timeout的使用方法
response = requests.get(url, timeout=3)
-
timeout=3表示:发送请求后,3秒钟内返回响应,否则就抛出异常
import requests url = 'https://twitter.com' response = requests.get(url, timeout=3) # 设置超时时间
requests发送post请求的方法
-
response = requests.post(url, data)
-
data
参数接收一个字典 -
requests模块发送post请求函数的其它参数和发送get请求的参数完全一致
BeautifulSoup
BeautifulSoup官方文档 https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间.
常见解释器的优缺点
常用操作
安装方法
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple beautifulsoup4
导入即可
from bs4 import BeautifulSoup
html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """
soup = BeautifulSoup(html_doc,"lxml")
几个简单的浏览结构化数据的方法
soup.title
<title>The Dormouse's story</title>
soup.title.name
'title'
soup.title.string
"The Dormouse's story"
soup.title.text
"The Dormouse's story"
soup.title.parent.name
'head'
soup.p
<p class="title"><b>The Dormouse's story</b></p>
soup.p.name
'p'
soup.p["class"]
['title']
soup.a
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
soup.find("a")
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
soup.find_all("a")
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
从文档中找到所有的< a>标签的链接
for link in soup.find_all("a"): print(link.get("href"))
http://example.com/elsie http://example.com/lacie http://example.com/tillie
在文档中获取所有的文字内容
print(soup.get_text())
The Dormouse's story The Dormouse's story Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well. ...
通过标签和属性获取
- Tag有很多方法和属性,在 遍历文档树 和 搜索文档树 中有详细解释.现在介绍一下tag中最重要的属性: name和attributes
soup = BeautifulSoup('<b class="boldest">Extremely bold</b>') tag = soup.b tag
<b class="boldest">Extremely bold</b>
type(tag)
bs4.element.Tag
Name属性
- 每个tag都有自己的名字,通过 .name 来获取:
tag.name
'b'
- 如果改变了tag的name,那将影响所有通过当前Beautiful Soup对象生成的HTML文档
tag.name = "blockquote" tag
<blockquote class="boldest">Extremely bold</blockquote>
多个属性
- 一个tag可能有很多个属性.tag 有一个 “class” 的属性,值为 “boldest” . tag的属性的操作方法与字典相同:
tag["class"]
['boldest']
tag.attrs
{'class': ['boldest']}
- tag的属性可以被添加,删除或修改. 再说一次, tag的属性操作方法与字典一样
tag["class"] = "verybold" tag["id"] = 1 tag
<blockquote class="verybold" id="1">Extremely bold</blockquote>
del tag["class"] tag
<blockquote id="1">Extremely bold</blockquote>
多值属性
css_soup = BeautifulSoup('<p class="body strikeout"></p>') css_soup.p['class']
['body', 'strikeout']
css_soup = BeautifulSoup('<p class="body"></p>') css_soup.p['class']
['body']
可以遍历的字符串
- 字符串常被包含在tag内.Beautiful Soup用 NavigableString 类来包装tag中的字符串:
tag.string
'Extremely bold'
type(tag.string)
bs4.element.NavigableString
-
一个 NavigableString 字符串与Python中的Unicode字符串相同,
并且还支持包含在遍历文档树 和 搜索文档树 中的一些特性.
通过 unicode() 方法可以直接将 NavigableString 对象转换成Unicode字符串: -
tag中包含的字符串不能编辑,但是可以被替换成其他的字符串,用replace_with()方法
tag.string.replace_with("No longer bold") tag
<blockquote id="1">No longer bold</blockquote>
注释及特殊字符串
- 文档的注释部分
markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>" soup = BeautifulSoup(markup) comment = soup.b.string comment
'Hey, buddy. Want to buy a used parser?'
type(comment)
bs4.element.Comment
- Comment 对象是一个特殊类型的 NavigableString 对象:
comment
'Hey, buddy. Want to buy a used parser?'
但是当它出现在HTML文档中时, Comment 对象会使用特殊的格式输出:
print(soup.prettify())
<html> <body> <b> <!--Hey, buddy. Want to buy a used parser?--> </b> </body> </html>
from bs4 import CData cdata = CData("A CDATA block") comment.replace_with(cdata) print(soup.b.prettify())
<b> <![CDATA[A CDATA block]]> </b>
遍历文档树
html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc,"html.parser")
子节点
一个Tag可能包含多个字符串或其它的Tag,这些都是这个Tag的子节点.Beautiful Soup提供了许多操作和遍历子节点的属性.
soup.head
<head><title>The Dormouse's story</title></head>
soup.title
<title>The Dormouse's story</title>
这是个获取tag的小窍门,可以在文档树的tag中多次调用这个方法.下面的代码可以获取标签中的第一个标签:
soup.body.b
<b>The Dormouse's story</b>
通过点取属性的方式只能获得当前名字的第一个tag:
soup.a
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
find_all方法
如果想要得到所有的标签,或是通过名字得到比一个tag更多的内容的时候,就需要用到 Searching the tree 中描述的方法,比如: find_all()
soup.find_all("a")
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
.contents和.children
head_tag = soup.head head_tag
<head><title>The Dormouse's story</title></head>
head_tag.contents
[<title>The Dormouse's story</title>]
head_tag.contents[0]
<title>The Dormouse's story</title>
head_tag.contents[0].contents
["The Dormouse's story"]
selenium
selenium官方文档 https://www.selenium.dev/selenium/docs/api/py/api.html
selenium介绍
chrome浏览器的运行效果
在下载好chromedriver以及安装好selenium模块后,执行下列代码并观察运行的过程
from selenium import webdriver # 如果driver没有添加到了环境变量,则需要将driver的绝对路径赋值给executable_path参数 # driver = webdriver.Chrome(executable_path='/home/worker/Desktop/driver/chromedriver') # 如果driver添加了环境变量则不需要设置executable_path driver = webdriver.Chrome() # 向一个url发起请求 driver.get("http://www.itcast.cn/") # 把网页保存为图片,69版本以上的谷歌浏览器将无法使用截图功能 # driver.save_screenshot("itcast.png") print(driver.title) # 打印页面的标题 # 退出模拟浏览器 driver.quit() # 一定要退出!不退出会有残留进程!
phantomjs无界面浏览器的运行效果
PhantomJS 是一个基于Webkit的“无界面”(headless)浏览器,它会把网站加载到内存并执行页面上的 JavaScript。下载地址:http://phantomjs.org/download.html
from selenium import webdriver # 指定driver的绝对路径 driver = webdriver.PhantomJS(executable_path='/home/worker/Desktop/driver/phantomjs') # driver = webdriver.Chrome(executable_path='/home/worker/Desktop/driver/chromedriver') # 向一个url发起请求 driver.get("http://www.itcast.cn/") # 把网页保存为图片 driver.save_screenshot("itcast.png") # 退出模拟浏览器 driver.quit() # 一定要退出!不退出会有残留进程!
无头浏览器与有头浏览器的使用场景
- 通常在开发过程中我们需要查看运行过程中的各种情况所以通常使用有头浏览器
- 在项目完成进行部署的时候,通常平台采用的系统都是服务器版的操作系统,服务器版的操作系统必须使用无头浏览器才能正常运行
selenium的作用和工作原理
利用浏览器原生的API,封装成一套更加面向对象的Selenium WebDriver API,直接操作浏览器页面里的元素,甚至操作浏览器本身(截屏,窗口大小,启动,关闭,安装插件,配置证书之类的)
selenium的安装以及简单使用
以edge浏览器为例 参见这个blog哦,驱动chrome浏览器同理
selenium驱动edge浏览器- chromedriver环境的配置
- windows环境下需要将 chromedriver.exe 所在的目录设置为path环境变量中的路径
- linux/mac环境下,将 chromedriver 所在的目录设置到系统的PATH环境值中
selenium的简单使用
接下来我们就通过代码来模拟百度搜索
import time from selenium import webdriver # 通过指定chromedriver的路径来实例化driver对象,chromedriver放在当前目录。 # driver = webdriver.Chrome(executable_path='./chromedriver') # chromedriver已经添加环境变量 driver = webdriver.Chrome() # 控制浏览器访问url地址 driver.get("https://www.baidu.com/") # 在百度搜索框中搜索'python' driver.find_element_by_id('kw').send_keys('python') # 点击'百度搜索' driver.find_element_by_id('su').click() time.sleep(6) # 退出浏览器 driver.quit()
webdriver.Chrome(executable_path='./chromedriver')
中executable参数指定的是下载好的chromedriver文件的路径driver.find_element_by_id('kw').send_keys('python')
定位id属性值是’kw’的标签,并向其中输入字符串’python’driver.find_element_by_id('su').click()
定位id属性值是su的标签,并点击- click函数作用是:触发标签的js的click事件
值是’kw’的标签,并向其中输入字符串’python’
driver.find_element_by_id('su').click()
定位id属性值是su的标签,并点击- click函数作用是:触发标签的js的click事件
使用xpath来提取数据,爬取数据的简单语法。
lxml
requests官方文档 https://lxml.de/
pip install lxml
- 导入模块
from lxml import etree
- 利用xpath获取text或者href内容
/li/a/@href 这样取的应该是href的内容 /li/a/text() 这样取得是text内容
etree的使用
h=etree.HTML(response.text)#response.text是网页的源码 h.xpath('//img') #寻找所有的img结点, h.xpath('//div').xpath('.//img')#寻找所有div下的所有img结点
xpath的语法
符号
XPath 使用路径表达式在 XML 文档中选取节点。节点是通过沿着路径或者 step 来选取的。表达式 描述 / 从根节点选取 // 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。 . 选取当前节点。 . . 选取当前节点的父节点。 @ 选取属性。 | 在两个中结点中选择 () 用()来包含| * 包含所有元素 not 取反 实例
路径表达式 结果 bookstore 选取 bookstore 元素的所有子节点。 /bookstore 选取根元素 bookstore。注释:假如路径起始于正斜杠( / ),则此路径始终代表到某元素的绝对路径! bookstore/book 选取属于 bookstore 的子元素的所有 book 元素。 //book 选取所有 book 子元素,而不管它们在文档中的位置。 bookstore//book 选择属于 bookstore 元素的后代的所有 book 元素,而不管它们位于 bookstore 之下的什么位置。 //@lang 选取名为 lang 的所有属性。 //*[@class] 选取带有class属性的所有元素 //div[@*] 匹配任意属性的div元素 //a[not(@class)] 匹配没有class属性的a元素 谓语
带谓语的路径表达式路径表达式 结果 /bookstore/book[1] 选取属于 bookstore 子元素的第一个 book 元素。 /bookstore/book[last()] 选取属于 bookstore 子元素的最后一个 book 元素。 /bookstore/book[last()-1] 选取属于 bookstore 子元素的倒数第二个 book 元素。 /bookstore/book[position()< 3] 选取最前面的两个属于 bookstore 元素的子元素的 book 元素。 //title[@lang] 选取所有拥有名为 lang 的属性的 title 元素。 //title[@lang=‘eng’] 选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。 /bookstore/book[price>35.00] 选取 bookstore 元素的所有 book 元素,且其中的 price 元素的值须大于 35.00。 /bookstore/book[price>35.00]/title 选取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值须大于 35.00。 到这里就结束了,如果对你有帮助你。当然学无止境,这些只是爬虫的基础,更多姿势需要你自己去探索呦。https://beishan.blog.csdn.net/
- Tableau数据分析-Chapter01条形图、堆积图、直方图
- Tableau数据分析-Chapter02数据预处理、折线图、饼图
- Tableau数据分析-Chapter03基本表、树状图、气泡图、词云
- Tableau数据分析-Chapter04标靶图、甘特图、瀑布图
- Tableau数据分析-Chapter05数据集合并、符号地图
- Tableau数据分析-Chapter06填充地图、多维地图、混合地图
- Tableau数据分析-Chapter07多边形地图、背景地图
- Tableau数据分析-Chapter08数据分层、数据分组、数据集
- Tableau数据分析-Chapter09粒度、聚合与比率
- Tableau数据分析-Chapter10 人口金字塔、漏斗图、箱线图
- Tableau数据分析-Chapter11 范围-线图、倾斜图
- Tableau数据分析-Chapter12 网络图、弧线图
- Tableau数据分析-Chapter13雷达图、凹凸图
- Tableau数据分析-Chapter14线性回归、时间序列分析
-
requests-2.22.0.tar.gz
2020-02-07 21:43:00最新版requests模块。 requests是使用Apache2 licensed 许可证的HTTP库。 用python编写。 比urllib2模块更简洁。 Request支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动响应内容的... -
Python网络爬虫Requests库入门
2020-12-21 12:56:51目录Requests库入门Requests库安装HTTP协议Requests库方法爬取网页的通用代码框架Requests库实战 Requests库入门 Requests库安装 pip install requests Requests库的安装测试: >>> import requests >>> r = ... -
解决已经安装requests,却依然提示No module named requests问题
2020-12-25 00:54:21pip install requests 之后依然提示 Python ImportError: No module named ‘requests’ 经过文件搜索和提示,发现是因为安装目录不正确。 一定要切到Python的主目录下安装requests。 如果提示已经安装,那原因是... -
python 爬虫请求模块requests详解
2020-12-16 19:38:22requests 相比urllib,第三方库requests更加简单人性化,是爬虫工作中常用的库 requests安装 初级爬虫的开始主要是使用requests模块 安装requests模块: Windows系统: cmd中: pip install requests mac系统中: ... -
requests
2022-04-06 18:04:00“”" 五、requests 1、什么是接口:用来传输数据的通道 examples 41 data3=“41” data2=“examples” data1=“{}{}”,format(data2,data3) 2、http请求的接口 ...“”"
五、requests
1、什么是接口:用来传输数据的通道
examples
41
data3=“41”
data2=“examples”
data1=“{}{}”,format(data2,data3)2、http请求的接口
https://www.ketangpai.com/#/main/classDetail?courseid=MDAwMDAwMDAwMLOGtZWGz6-yhdtyoQ&courserole=1&submodulename=0
拆解:
https://:协议
www.ketangpai.com:域名
/#/main/classDetail:接口地址
courseid=MDAwMDAwMDAwMLOGtZWGz6-yhdtyoQ&courserole=1&submodulename=0:参数3、http请求的三要素
1、请求地址
2、请求方法
3、请求数据4、requests请求接口
1、安装requests
pip install requests2、发一个get请求
会将请求参数自动拼接到接口地址后面
data = {“key1”:“val1”,“key2”:“val2”}
res = requests.get(url=“http://httpbin.org/get?key1=val1&key2=val2”)
res = requests.get(url=“http://httpbin.org”,params=data)3、post请求
res = requests.post(url=“http://httpbin.org/post”,data=data)
data:默认使用{‘Content-Type’: ‘application/x-www-form-urlencoded’}
如果设置了请求头的Content-Type,那么就按照设置的编码方法进行传参
json:默认使用{‘Content-Type’: ‘application/json’}
如果设置了请求头的Content-Type,那么就按照设置的编码方法进行传参4、如何发送https请求
res = requests.post(url=“http://httpbin.org/post”,data=data,verify=False)面试题
get与post的区别
安全性:
1、get传参放在接口地址后面(浏览器地址后面),相对来说不那么安全
2、post请求数据藏起来的,放在请求体里面(body)
使用场景
3、get请求一般用于获取数据
4、post请求用于提交数据
参数长度
5、get请求一般参数有长度限制,后端服务器做的限制
6、post请求参数也有长度限制,后端服务器做的限制(post参数长度一般大于get)
幂等性
7、幂等性:同一个接口,同一个参数请求N遍,返回结果都不会变
get请求都是幂等的
post请求一般是不幂等的(支付、注册、提现这类接口要做幂等处理)http与https的区别
1、http是明文传输,https传输加密的
2、http默认80端口,https默认443端口
3、https需要CA证书,一般证书要收费
4、http是无状态的简单的协议
5、https有状态的,需要验证身份
6、HTTPS = http+加密+ssl认证
“”"import requests
import pprinthead={‘Content-Type’: ‘application/x-www-form-urlencoded’}
head={‘Content-Type’: ‘application/json’}
data = {“key1”:“val1”,“key2”:{“key3”:“val3”}}
res = requests.post(url=“http://httpbin.org/post”,data=data)res = requests.post(url=“http://httpbin.org/post”,json=data)
pprint.pprint(res.json())
res = requests.post(url=“http://httpbin.org/post”,data=data,verify=False)
“”"
get请求
data = {“key1”:“val1”,“key2”:“val2”}res = requests.get(url=“http://httpbin.org/get?key1=val1&key2=val2”)
res = requests.get(url=“http://httpbin.org/get”,params=data)
pprint.pprint(res.json())
“”" -
Requests库爬虫详解
2021-11-22 09:52:29关于requests: 官方的解释是:Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用。 作用: Requests 完全满足今日 web 的需求。 Keep-Alive & 连接池 国际化域名和 URL 带持久 Cookie 的...关于requests:
官方的解释是:Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用。
作用:
Requests 完全满足今日 web 的需求。
- Keep-Alive & 连接池
- 国际化域名和 URL
- 带持久 Cookie 的会话
- 浏览器式的 SSL 认证
- 自动内容解码
- 基本/摘要式的身份认证
- 优雅的 key/value Cookie
- 自动解压
- Unicode 响应体
- HTTP(S) 代理支持
- 文件分块上传
- 流下载
- 连接超时
- 分块请求
- 支持
.netrc
安装:
pip instsall requests #适用Python3
Requests的使用方法:
实例说明:
import requests response=requests.get('https://www.baidu.com') print(type(response)) print(response.status_code) print(type(response.text)) print(response.text) print(response.cookies)
返回结果:
各种请求方式:
import requests requests.post('http://httpbin.org/post') requests.put('http://httpbin.org/put') requests.delete('http://httpbin.org/delete') requests.head('http://httpbin.org/get') requests.options('http://httpbin.org/get')
基本的get请求:
import requests response=requests.get('http://httpbin.org/get')#用get方式发送请求并获得响应 print(response.text)#用text查看响应内容
返回结果:
带参数的get请求:
import requests data={ 'name':'zhuzhu', 'age':23 } response=requests.get('http://httpbin.org/get',params=data) #用字典的形式传递给params参数,不需要自己写url编码 print(response.text)
返回结果:
解析json:
import requests response=requests.get("http://httpbin.org/get") print(type(response.text)) print(response.json())#把返回结果编码成一个json对象 print(type(response.json()))
返回结果:
备注:使用于返回一些AJEX请求时是比较常用的。
获取二进制数据:
在下载一些内容(图片、视频)的时候常用的一个方法。
试试看,我们想要获取一个github的图标:import requests response=requests.get("https://github.com/favicon.ico") print(type(response.text),type(response.content)) print(response.text) print(response.content)#可以使用content属性来获取二进制内容
返回结果:
可以看到,在响应中,text的类型是string,而content的内容是bytes,也就是二进制形式。
怎么把这个图标保存到本地呢?我们已经知道怎么获取它的二进制内容,现在只需要写入文件就可以了import requests response=requests.get("https://github.com/favicon.ico") with open('favicon.ico','wb')as f: f.write(response.content) f.close()
运行后就可以看到favicon.ico 的文件了
基本POST请求:
用字典的形式构建一个data,并将方法传入,来实现post请求(类似get在url中加入parmes一样)
import requests data={'name':'zhuzhu','age':'23'} headers={ 'User-Agent':'Mozilla/5.0(Macintosh;Intel Mac OS X 10_11_4)AppleWebKit/537.36(KHTML,like Gecko)Chrome/52.0.2743.116 Safari/537.36' } response=requests.post("http://httpbin.org/post",data=data,headers=headers) print(response.json())
可以看到,返回的json形式的响应中,我们成功添加了data和headers的信息。
添加headers头:
为了防爬虫,很多网址通常会对headers头进行识别,因此我们需要增加Headers头进行伪装。比如说:
import requests response=requests.get("https://www.zhihu.com/explore") print(response.text)
返回的结果:
现在我们来加入HEADERS头进行伪装:
import requests headers={ 'User-Agent':'Mozilla/5.0(Macintosh;Intel Mac OS X 10_11_4)AppleWebKit/537.36(KHTML,like Gecko)Chrome/52.0.2743.116 Safari/537.36' } response=requests.get("https://www.zhihu.com/explore",headers=headers) print(response.text)
返回的结果:
响应:
import requests response=requests.get("http://www.baidu.com") if not response.status_code==200: print('请求响应失败') else: print("Requests 请求成功")
运行后成功,说明响应是200,是成功获取了。
文件上传
import requests files={'file':open('favicon.ico','rb')} #通过files参数传入post方法中,实现文件的上传 response=requests.post("http://httpbin.org/post",files=files) print(response.text)
这样通过post请求,我们就完成了文件的上传,下图file显示的就是文件的字节流了:
获取cookie:
import requests response=requests.get("http://www.baidu.com") print(response.cookies) for key,value in response.cookies.items(): print(key+'='+value)
返回结果:
会话保持:
作用:基本上为了实现“模拟登录”的功能。
例子:
import requests requests.get('http://httpbin.org/cookies/set/number/123456789') #通过cookies/set方法来设置cookie response=requests.get('http://httpbin.org/cookies') print(response.text)
返回空cookie
cookies为空,这是因为上面那段代码中发起了两次get请求,相当于两个浏览器,相互独立,所以第二次get并不能得到第一次的cookie。
可以通过声明Session对象来发起两次get请求,视为一个浏览器中进行的操作:import requests s=requests.Session() #定义一个变量s s.get('http://httpbin.org/cookies/set/number/123456789') #通过cookies/set方法来设置cookie response=s.get('http://httpbin.org/cookies') print(response.text)
证书验证
如果我们要爬取的是一个https协议的网站,那么网站首先会检查证书是否是合法的,若非法,会直接抛出SSLError错误。如果要避免这种错误的话,可以把这个参数:verify设置为False就可以了(默认是True)。
import requests response=requests.get('https://www.12306.cn',verify=False)#把verify参数置否 print(response.status_code)
代理设置
可以通过字典形式构造一个参数,字典里是你已经开通的代理ip。再把参数传入get方法即可。
import requests proxies={ "http":"http://127.0.0.1:9743", "https":"https://127.0.0.1:9743" } response=requests.get("https://www.taobao.com",proxies=proxies) print(response.status_code)
如果代理需要用户名和密码的时候怎么办呢?
我们可以在代理的url前面直接传一个user:password,后面加个@符号,这样我们就能传入用户名和密码这个认证信息了:proxies={ "http":"http://uesr:password@127.0.0.1:9743/", }
那如果代理方式不是https,而是一个socks类型的呢?
首先需要安装,在命令行执行(windows环境下):
pip3 install request[socks]
安装之后就可以使用这种形式的代理了。import requests proxies={ "http":"sock5://127.0.0.1:9743", "https":"socks5://127.0.0.1:9743" } response=requests.get("https://www.taobao.com",proxies=proxies) print(response.status_code)
超时设置:
import requests response=requests.get("https://www.taobao.com",timeout=1) #设置一个时间限制,必须在1秒内得到应答 print(response.status_code)
如果时间超出了限制,就会抛出异常。怎么捕获这个异常呢?
import requests from requests.exceptions import ReadTimeout try: response=requests.get("https://httpbin.org/get",timeout=0.5) print(response.status_code) except ReadTimeout: print('Timeout')
认证设置:
作用:有的网站在访问时需要输入用户名和密码,输入之后才能看到网站的内容。
如果遇到这种网站,我们可以通过auth参数,把用户名和密码传入。import requests from requests.auth import HTTPBasicAuth r=requests.get('http://120.27.34.24:9001',auth=HTTPBasicAuth('user','123')) #通过auth参数传入。 print(r.status_code)
这样就可以完成一个正常的请求,如果把auth参数去掉,那么就会返回401参数(请求被禁止)。
异常处理
异常处理的部分还是比较重要的,它可以保证你的爬虫不间断地运行。
原则还是先捕获子类异常,再捕捉父类异常(RequestException)。import requests from requests.exceptions import ReadTimeout,HTTPError,RequestException try: response=requests.get('http://httpbin.org/get',timeout=0.1) print(response.status_code) except ReadTimeout:#捕获超时异常 print('Timeout') except HTTPError:#捕获HTTP异常 print('Http error') except ConnectionError:#捕获连接异常 print('Connection error') except RequestException:#捕获父类异常 print('Error')
-
【Python技能树共建】requests-html库初识
2022-05-06 13:52:14requests-html 模块安装使用 pip install requests-html 即可,官方手册查询地址:requests-html.kennethreitz.org/,官方并没有直接的中文翻译,在检索过程中,确实发现了一版中文手册,在文末提供。 先看一下官方... -
pythonrequests快速入门
2018-08-05 09:02:24pythonrequests快速入门pythonrequests快速入门pythonrequests快速入门pythonrequests快速入门 -
【python教程】requests库的基本用法
2022-04-13 22:44:03requests是一个很实用的Python HTTP客户端库,爬虫和测试服务器响应数据时经常会用到,requests是Python语言的第三方的库,专门用于发送HTTP请求,使用起来比urllib简洁很多。 往期知识点 往期内容回顾 python... -
python requests模块详解
2021-02-03 05:56:05requests是Python的一个HTTP客户端库,跟urllib,urllib2类似,那为什么要用requests而不用urllib2呢...我也看了下requests的文档,确实很简单,适合我这种懒人。下面就是一些简单指南。插播个好消息!刚看到reques... -
requests库的使用(一篇就够了)
2022-01-05 20:30:26为了更加方便的实现这些操作,就有了更为强大的requests库。 基本用法 请先参考requests库安装一节,确保安装了requests库。下面案例使用requests库中的get( )方法发送了一个get请求。 #导入requests库 import ... -
爬虫学习(3):两万字零基础爬虫requests初阶教程,手把手教你爬数据
2021-10-13 12:19:46文章目录一、环境与工具二、学爬虫必备知识三、requests体验四、get 请求3.1 基础讲解一3.3 基础讲解二3.2 基础讲解三3.4 获取cookie3.5 获取请求头3.6 添加请求头3.5 知乎爬取+反扒技术3.6 抓取二进制数据3.6.1 ... -
全网最全requests库和requests模块使用详解
2020-06-19 14:55:11一 、requests简介 #简介:使用requests可以模拟浏览器的请求,比起之前用的urllib,requests模块的api更加便捷(本质就是封装了urllib3) #注意:requests库发送请求将网页内容下载下来以后,并不会执行js代码... -
Requests库介绍
2020-12-12 13:43:31Requests 是用Beautiful is better than ugly.(美丽优于丑陋)Explicit is better than implicit.(清楚优于含糊)Simple is better than complex.(简单优于复杂)Complex is better than complicated.(复杂优于繁琐)... -
爬虫中requests模块(一)
2021-11-12 21:29:03一、requests模块介绍 1.requests模块的作用 发送http请求,获取响应数据。 2.安装 pip/pip3 install requests 3.发送get请求 导入requests模块 调用get方法,对目标url发送请求。 例: # 调用requests... -
【转载】爬虫篇——requests的基础知识(总结)
2022-04-18 20:27:23import requests res = requests.get('https://www.python.org') print(type(res)) # <class 'requests.models.Response'> print(res.status_code) # 200 print(type(res.text)) # <class 'str'> print... -
你肯定听说过requests,但你知道2022年有一个比 requests 还牛的爬虫库吗?
2022-03-21 11:24:55⛳️ 准备工作 任何模块学习前,都需要执行下述两个步骤 模块简介 模块安装 帮助手册的准备 HTTPX 是最近接触到的一个 Python 请求模块,其特点如下所示 兼容 requests,语法类似 支持 HTTP/1.1 和 HTTP/2 严格超时...