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库发送请求将网页内 ...
随机推荐
- SpringBoot Mybatis问题收集
1.在SpringBoot中打印mybatis中执行的sql 其实在application.properties 文件下,添加一下配置即可: logging.level.org.springframe ...
- python 之 条件语句
python 编程语言指定任何非0和非空(null)值为true, 0或者null为false. python 编程中if语句用于控制程序的执行,基本形式为: if 判断条件: 执行语句…… else ...
- P3159 [CQOI2012]交换棋子
思路 相当神奇的费用流拆点模型 最开始我想到把交换黑色棋子看成一个流流动的过程,流从一个节点流向另一个节点就是交换两个节点,然后把一个位置拆成两个点限制流量,然后就有了这样的建图方法 S向所有初始是黑 ...
- [thymeleaf] - 1.Thymeleaf是什么
Thymeleaf是⾯向Web和独⽴环境的现代服务器端Java模板引擎,能够处 理HTML,XML,JavaScript,CSS甚⾄纯⽂本. Thymeleaf旨在提供⼀个优雅的.⾼度可维护的创建模板 ...
- JavaScript基本内容
注释: /*多行 注释*/ //单行注释 变量: //变量均为对象,常用类型:String.Number.Boolean.Array.Object var value = "hello&qu ...
- Codeforces 786 C. Till I Collapse
题目链接:http://codeforces.com/contest/786/problem/C 大力膜了一发杜教的代码感觉十分的兹瓷啊! 我们知道如果$k$是给定的我们显然是可以直接一遍$O(n)$ ...
- activity 运行流程图
- MySQL中字符串和数字拼接
select * from qa_employ where EMPLOY_GROUP =2 原先雇佣表中所有雇佣姓名全部是"张三", 希望将雇用姓名变得不一样,比如张三+id SQ ...
- CentOS7下搭建Nginx+PHP7的安装配置
一.安装编译工具及库文件: yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel 环境要求 nginx是C ...
- 学习笔记58—3D杯子设计
软件下载:http://www.i3done.com/ 界面如下: 3D杯子设计步骤(参考:http://www.i3done.com/news/video/402.html): 生成杯体 1.点击基 ...