2 爬虫 requests模块
requests模块
Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库,Requests它会比urllib更加方便,requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库。
1.安装:
pip install requests
2.基本语法
1.request模块支持的请求:
import requests
requests.get("http://httpbin.org/get")
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请求
1 基本请求
import requests
response=requests.get('https://www.jd.com/',) with open("jd.html","wb") as f:
f.write(response.content)
2 含参数请求
import requests
response=requests.get('https://s.taobao.com/search?q=手机')
response=requests.get('https://s.taobao.com/search',params={"q":"美女"})
3 含请求头请求
mport requests
response=requests.get('https://dig.chouti.com/',
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36',
}
)
4 含cookies请求
import uuid # 生成随机字符串的模块
import requests url = 'http://httpbin.org/cookies'
cookies = dict(sbid=str(uuid.uuid4())) res = requests.get(url, cookies=cookies)
print(res.text) # cookie 的用法 :
res =requests.get("https://www.autohome.com.cn/beijing/")
res_cookies=res.cookies
requests.post("https://www.autohome.com.cn/beijing/",cookies=res_cookies)
5.session请求
# 相当于上面cookie的用法过程
session=requests.session()
res1 = session.gett("https://github.com/login/")
res2 =session.post("https://github.com/session",headers=header,data=data)
post请求
1 data参数
requests.post()用法与requests.get()完全一致,特殊的是requests.post()多了一个data参数,用来存放请求体数据
response=requests.post("http://httpbin.org/post",params={"a":"1"}, data={"name":"deng"})
2 发送json数据
mport requests
res1=requests.post(url='http://httpbin.org/post', data={'name':'deng'}) #没有指定请求头,#默认的请求头:application/x-www-form-urlencoed
print(res1.json()) res2=requests.post(url='http://httpbin.org/post',json={'age':"11",}) #默认的请求头:application/json
print(res2.json())
response对象
(1) 常见属性
import requests
respone=requests.get('https://sh.lianjia.com/ershoufang/')
# respone属性
print(respone.text) # 解码后的
print(respone.content) # 字节类型的
print(respone.status_code) # 响应状态码
print(respone.headers) # 请求头数据
print(respone.cookies) # i cookies
print(respone.cookies.get_dict())
print(respone.cookies.items())
print(respone.url)
print(respone.history) # 重定向之前的
print(respone.encoding) # 编码
(2) 编码问题
import requests
response=requests.get('http://www.autohome.com/news')
#response.encoding='gbk' #汽车之家网站返回的页面内容为gb2312编码的,而requests的默认编码为ISO-8859-1,如果不设置成gbk则中文乱码
with open("res.html","w") as f:
f.write(response.text)
(3) 下载二进制文件(图片,视频,音频)
import requests
response=requests.get('http://bangimg1.dahe.cn/forum/201612/10/200447p36yk96im76vatyk.jpg')
with open("res.png","wb") as f:
# f.write(response.content) # 比如下载视频时,如果视频100G,用response.content然后一下子写到文件中是不合理的
for line in response.iter_content(): # 生成器
f.write(line)
(4) 解析json数据
import requests
import json response=requests.get('http://httpbin.org/get')
res1=json.loads(response.text) #太麻烦
res2=response.json() #直接获取json数据
print(res1==res2)
(5) Redirection and History
默认情况下,除了 HEAD, Requests 会自动处理所有重定向。可以使用响应对象的 history 方法来追踪重定向。Response.history 是一个 Response 对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。
>>> r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[<Response [301]>]
另外,还可以通过 allow_redirects 参数禁用重定向处理:
>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]
requests进阶用法
代理
快代理: https://www.kuaidaili.com/free/
一些网站会有相应的反爬虫措施,例如很多网站会检测某一段时间某个IP的访问次数,如果访问频率太快以至于看起来不像正常访客,它可能就会会禁止这个IP的访问。所以我们需要设置一些代理服务器,每隔一段时间换一个代理,就算IP被禁止,依然可以换个IP继续爬取
res=requests.get('http://httpbin.org/ip', proxies={'http':'110.83.40.27:9999'}).json()
print(res)
爬虫案例
github的home页
#解决问题的思路:
#先用自己的账户登录GitHub ,去找需要带上的请求信息
#分析需要带上的请求信息,此处最关键的点是:登录时将数据提交到哪个url ,数据中authenticity_token 如何动态获取 # 获取登录页面
url ='https://github.com/login' # 登录地址
session=requests.session()
login = session.get(url) # 构建数据
authenticity_token=re.findall('name="authenticity_token" value="(.*?)"',login.text)
data={
'commit': 'Sign in',
'utf8': '✓',
'authenticity_token': authenticity_token,
'login': 'dengjn',
'password': 'd11111'}
header={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'
} res2 =session.post("https://github.com/session",headers=header,data=data) with open("github.html","wb") as f:
f.write(res2.content)
print(login.status_code)
print(res2.status_code)
方式2:
import requests from bs4 import BeautifulSoup # get 请求拿登录页面 ,并且通过标签找到 token
login_url ="https://github.com/login"
res1 =requests.get(login_url)
soup = BeautifulSoup(res1.text)
token=soup.find(name="input",attrs={"name":"authenticity_token"}).get("value") # name="input" 此name表示标签名
cookies1=res1.cookies.get_dict()#拿cookie # post 的请求 去登录 ,需要带参数过去,请求页面 form表单的action 会有
'''
commit: Sign in
utf8: ✓
authenticity_token: PiH1kMaw3MUDqQ==
login: dengjiyun
password: dsgasg
''' form_data={
"commit":"Sign in",
"authenticity_token":token,
"utf8":"✓",
"login":"dengjiyun",
"password":"dsdgfg",
}
url2 ="https://github.com/session" r2 =requests.post(url2,data=form_data,cookies=cookies1)
print(r2.status_code) cookies={} # 总cookies
# 将获取登录页面请求需要的cookies1和登录后的cookies合在一起
cookies2= r2.cookies.get_dict()
cookies.update(cookies1)
cookies.update(cookies2) r3 =requests.get( url='https://github.com/new',cookies=cookies)
with open("git.html","wb") as f:
f.write(r3.content)
2 爬虫 requests模块的更多相关文章
- 爬虫 requests模块的其他用法 抽屉网线程池回调爬取+保存实例,gihub登陆实例
requests模块的其他用法 #通常我们在发送请求时都需要带上请求头,请求头是将自身伪装成浏览器的关键,常见的有用的请求头如下 Host Referer #大型网站通常都会根据该参数判断请求的来源 ...
- 爬虫——requests模块
一 爬虫简介 #1.什么是互联网? 互联网是由网络设备(网线,路由器,交换机,防火墙等等)和一台台计算机连接而成,像一张网一样. #2.互联网建立的目的? 互联网的核心价值在于数据的共享/传递:数据是 ...
- 爬虫--requests模块高级(代理和cookie操作)
代理和cookie操作 一.基于requests模块的cookie操作 引言:有些时候,我们在使用爬虫程序去爬取一些用户相关信息的数据(爬取张三“人人网”个人主页数据)时,如果使用之前requests ...
- 爬虫--requests模块学习
requests模块 - 基于如下5点展开requests模块的学习 什么是requests模块 requests模块是python中原生的基于网络请求的模块,其主要作用是用来模拟浏览器发起请求.功能 ...
- Python网络爬虫-requests模块(II)
有些时候,我们在使用爬虫程序去爬取一些用户相关信息的数据(爬取张三“人人网”个人主页数据)时,如果使用之前requests模块常规操作时,往往达不到我们想要的目的,例如: #!/usr/bin/env ...
- Python网络爬虫-requests模块
requests模块 requests模块是python中原生的基于网络请求的模块,其主要作用是用来模拟浏览器发起请求.功能强大,用法简洁高效.在爬虫领域中占据着半壁江山的地位. 如何使用reques ...
- 爬虫requests模块 1
让我们从一些简单的示例开始吧. 发送请求¶ 使用 Requests 发送网络请求非常简单. 一开始要导入 Requests 模块: >>> import requests 然后,尝试 ...
- 爬虫 requests 模块
requests 模块 介绍 使用requests可以模拟浏览器的请求, 比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3) ps: requests库发 ...
- 爬虫----requests模块
一.介绍 #介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3) #注意:requests库发送请求将网页内 ...
随机推荐
- 何为TLC、MLC、SLC?【转】
本文转载自:https://blog.csdn.net/weixin_38233274/article/details/79310316 1.一块SSD由主控.DRAM缓存和NAND闪存三种芯片所组成 ...
- tp框架中的一些疑点知识-8
NaN是Number对象的一个属性, 表示一个特殊值, 表示不是一个 数字, 引用/赋值时, 要使用: Number.NaN 判断 一个值是不是 NaN, 用 isNaN() 函数, 它是一个js的全 ...
- 【做题】arc068_e-Snuke Line——利用特殊性质分讨
显然,对于所有跨度暴力扫一遍的复杂度本身只有\(O(n \log n)\). 容易想到在每一个到达的位置加上覆盖这个位置的区间数.剩下的问题就在于如何处理覆盖了多个位置的区间. 记录已访问或去重都是难 ...
- P1829 [国家集训队]Crash的数字表格 / JZPTAB
推式子太快乐啦!虽然我好蠢而且dummy和maomao好巨(划掉) 思路 莫比乌斯反演的题目 首先这题有\(O(\sqrt n)\)的做法但是我没写咕咕咕 然后就是爆推一波式子 \[ \sum_{i= ...
- (转) RNN models for image generation
RNN models for image generation MARCH 3, 2017 Today we’re looking at the remaining papers from the ...
- Jenkins参数化构建(一)之 Maven Command Line传递TestNG构建参数
1. Maven使用 -D参数名称 将参数传递至所运行项目 Maven指定TestNg.xml文件 clean test -DsuiteXmlFile=src/main/resources/testn ...
- CART决策树
CART(Classification and Regression tree)分类回归树由L.Breiman,J.Friedman,R.Olshen和C.Stone于1984年提出.ID3中根据属 ...
- RN返回navigation方法
RN官方指定的路由管理是navigation 通过打印我们可以得到navgation的相关属性 1:dispatch ,Redux的事件发起 2:goback()返回 3:navigate(rout ...
- java stackoverflowerror与outofmemoryerror区别(转)
1.stackoverflow: 每当java程序启动一个新的线程时,java虚拟机会为他分配一个栈,java栈以帧为单位保持线程运行状态:当线程调用一个方法是,jvm压入一个新的栈帧到这个线程的栈中 ...
- 获取指定tag的代码
git checkout v1.0.3 再使用ls查看就可以了