爬虫之request模块

爬虫之request模块

request简介

#介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3)

#注意:requests库发送请求将网页内容下载下来以后,并不会执行js代码,这需要我们自己分析目标站点然后发起新的request请求

#安装:pip3 install requests

#各种请求方式:常用的就是requests.get()和requests.post()
>>> import requests
>>> r = requests.get(‘https://api.github.com/events‘)
>>> r = requests.post(‘http://httpbin.org/post‘, data = {‘key‘:‘value‘})
>>> r = requests.put(‘http://httpbin.org/put‘, data = {‘key‘:‘value‘})
>>> r = requests.delete(‘http://httpbin.org/delete‘)
>>> r = requests.head(‘http://httpbin.org/get‘)
>>> r = requests.options(‘http://httpbin.org/get‘)

#建议在正式学习requests前,先熟悉下HTTP协议
http://www.cnblogs.com/linhaifeng/p/6266327.html

基于GET请求

  • 基本请求

    import requests
    response=requests.get(‘http://dig.chouti.com/‘)
    print(response.text)
  • 带参数的get请求
  • headers--请求头
    • User-Agent
    • 我们要用爬虫来爬取数据究其本质就是通过脚本模拟浏览器来进行操作,在任何一个html界面我们通过f12来调用代码,通过network选项来找到请求头进行操作!

      一般的网站对于反扒都会加上最基本的User-Agent字段

```python

# 我们来模拟知乎搜索

import requests

reponse=requests.get(‘https://www.zhihu.com/explore‘,

headers={

‘User-Agent‘:‘Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36‘,

},

)

print(reponse.status_code)

print(reponse.text)


 - parms
   - 比如在浏览器中搜索时,因为浏览器不识别汉字,所以我们要进行转化
  - ```python
from urllib.parse import urlencode
params={
    ‘wd‘:‘美女‘,
}
url=‘https://www.baidu.com/s?%s‘ %urlencode(params,encoding=‘utf-8‘)
print(url)
  • 保存爬下来的数据

```python

reponse=requests.get(url,

headers={

‘User-Agent‘:‘Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36‘,

},

)

print(reponse.status_code) # 打印状态码 ## 状态码详解见下一篇文章

print(reponse.text)

reponse.encoding=‘utf-8‘

with open(‘test.html‘,‘w‘,encoding=‘utf-8‘) as f:

f.write(reponse.text)

   - 带参数的GET请求--cookies

   ```python
#登录github,然后从浏览器中获取cookies,以后就可以直接拿着cookie登录了,无需输入用户名密码
#用户名:egonlin 邮箱[email protected] 密码[email protected]

import requests

Cookies={   ‘user_session‘:‘wGMHFJKgDcmRIVvcA14_Wrt_3xaUyJNsBnPbYzEL6L0bHcfc‘,
}

response=requests.get(‘https://github.com/settings/emails‘,
             cookies=Cookies) #github对请求头没有什么限制,我们无需定制user-agent,对于其他网站可能还需要定制

print(‘[email protected]‘ in response.text) #True

基于POST的请求

  • post请求和get请求之间的对比
#GET请求
HTTP默认的请求方法就是GET
     * 没有请求体
     * 数据必须在1K之内!
     * GET请求数据会暴露在浏览器的地址栏中

GET请求常用的操作:
       1. 在浏览器的地址栏中直接给出URL,那么就一定是GET请求
       2. 点击页面上的超链接也一定是GET请求
       3. 提交表单时,表单默认使用GET请求,但可以设置为POST

#POST请求
(1). 数据不会出现在地址栏中
(2). 数据的大小没有上限
(3). 有请求体
(4). 请求体中如果存在中文,会使用URL编码!

#!!!requests.post()用法与requests.get()完全一致,特殊的是requests.post()有一个data参数,用来存放请求体数据
  • 发送POST请求,模拟浏览器的登录行为
一 目标站点分析
    浏览器输入https://github.com/login
    然后输入错误的账号密码,抓包
    发现登录行为是post提交到:https://github.com/session
    而且请求头包含cookie
    而且请求体包含:
        commit:Sign in
        utf8:?
        authenticity_token:lbI8IJCwGslZS8qJPnof5e7ZkCoSoMn6jmDTsL1r/m06NLyIbw7vCrpwrFAPzHMep3Tmf/TSJVoXWrvDZaVwxQ==
        login:egonlin
        password:123

二 流程分析
    先GET:https://github.com/login拿到初始cookie与authenticity_token
    返回POST:https://github.com/session, 带上初始cookie,带上请求体(authenticity_token,用户名,密码等)
    最后拿到登录cookie

    ps:如果密码时密文形式,则可以先输错账号,输对密码,然后到浏览器中拿到加密后的密码,github的密码是明文
‘‘‘

import requests
import re

#第一次请求
r1=requests.get(‘https://github.com/login‘)
r1_cookie=r1.cookies.get_dict() #拿到初始cookie(未被授权)
authenticity_token=re.findall(r‘name="authenticity_token".*?value="(.*?)"‘,r1.text)[0] #从页面中拿到CSRF TOKEN

#第二次请求:带着初始cookie和TOKEN发送POST请求给登录页面,带上账号密码
data={
    ‘commit‘:‘Sign in‘,
    ‘utf8‘:‘?‘,
    ‘authenticity_token‘:authenticity_token,
    ‘login‘:‘[email protected]‘,
    ‘password‘:‘22222222‘
}
r2=requests.post(‘https://github.com/session‘,
             data=data,
             cookies=r1_cookie
             )

login_cookie=r2.cookies.get_dict()

#第三次请求:以后的登录,拿着login_cookie就可以,比如访问一些个人配置
r3=requests.get(‘https://github.com/settings/emails‘,
                cookies=login_cookie)

print(‘111111111‘ in r3.text) #Tru

响应Response

  • response属性

```python

import requests

respone=requests.get(‘http://www.jianshu.com‘)

respone属性

print(respone.text) # 打印响应的页面的str

print(respone.content) # 打印响应的内容

print(respone.status_code) # 打印响应的状态码

print(respone.headers) # 打印头信息

print(respone.cookies) # 打印cookies

print(respone.cookies.get_dict()) # 打印字典形式的cookies

print(respone.cookies.items()) # 打印列表形式的字典

print(respone.url) # 打印url

print(respone.history) # 打印历史记录

print(respone.encoding) # 打印字符编码

关闭:response.close() # 关闭链接

from contextlib import closing

存储文件

with closing(requests.get(‘xxx‘,stream=True)) as response:

for line in response.iter_content():

pass

```

  • 编码问题
#编码问题
import requests
response=requests.get(‘http://www.autohome.com/news‘)
# response.encoding=‘gbk‘ #汽车之家网站返回的页面内容为gb2312编码的,而requests的默认编码为ISO-8859-1,如果不设置成gbk则中文乱码
print(response.text)
  • 获取二进制数据
import requests

response=requests.get(‘https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1509868306530&di=712e4ef3ab258b36e9f4b48e85a81c9d&imgtype=0&src=http%3A%2F%2Fc.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F11385343fbf2b211e1fb58a1c08065380dd78e0c.jpg‘)

with open(‘a.jpg‘,‘wb‘) as f:
    f.write(response.content)
  • 高级用法
  • 注:高级用法在这里只阐述代理用法,其他方法在实际生产环境中所用甚少
#官网链接: http://docs.python-requests.org/en/master/user/advanced/#proxies

#代理设置:先发送请求给代理,然后由代理帮忙发送(封ip是常见的事情)
import requests
proxies={
    ‘http‘:‘http://egon:[email protected]:9743‘,#带用户名密码的代理,@符号前是用户名与密码
    ‘http‘:‘http://localhost:9743‘,
    ‘https‘:‘https://localhost:9743‘,
}
respone=requests.get(‘https://www.12306.cn‘,
                     proxies=proxies)

print(respone.status_code)

#支持socks代理,安装:pip install requests[socks]
import requests
proxies = {
    ‘http‘: ‘socks5://user:[email protected]:port‘,
    ‘https‘: ‘socks5://user:[email protected]:port‘
}
respone=requests.get(‘https://www.12306.cn‘,
                     proxies=proxies)

print(respone.status_code)

原文地址:https://www.cnblogs.com/DE_LIU/p/8269991.html

时间: 2024-08-27 02:35:21

爬虫之request模块的相关文章

Python爬虫之request模块

1. 请求方式 # 介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3) # 注意:requests库发送请求将网页内容下载下来以后,并不会执行js代码,这需要我们自己分析目标站点然后发起新的request请求 1. Request = requests.rquest(method, url, **kwargs) # 构造一个请求 # ethod(6个) head/get/post/put/patch/d

request模块的简单使用+爬虫小程序

爬虫之request 各种请求方式 get host_url = 'https://www.pearvideo.com/' #浏览器的版本等信息 headers = { "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36" } res = requests.ge

第三百二十四节,web爬虫,scrapy模块介绍与使用

第三百二十四节,web爬虫,scrapy模块介绍与使用 Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中.其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的, 也可以应用在获取API所返回的数据(例如 Amazon Associates Web Services ) 或者通用的网络爬虫.Scrapy用途广泛,可以用于数据挖掘.监测和自动化测试. Scrapy 使用了 Twisted异步网络库来处理网络通讯.

Python的Request模块,请求跳过认证及禁用警告

最近在学python的爬虫,用到Requests模块.关于requests模块的优点,用过的人才知道!笔者用的python的版本时3.6.其他版本还未使用,请勿完全的对号入座,谢谢. 1.requests模块的官方文档:http://docs.python-requests.org/ 2.python中requests模块的安装:pip install requests  ---->若不指定版本,则默认是安装的python官方已发布的2.19.1.requests版本问题,涉及到了这篇博客的主题

Python爬虫教程-09-error 模块

Python爬虫教程-09-error模块 今天的主角是error,爬取的时候,很容易出现错,所以我们要在代码里做一些,常见错误的处,关于urllib.error URLError URLError 产生的原因: 1.无网络连接 2.服务器连接失败 3.找不到指定的服务器 4.URLError是OSError的子类 案例v9文件:https://xpwi.github.io/py/py%E7%88%AC%E8%99%AB/py09error.py # 案例v9 # URLError的使用 fro

web爬虫,scrapy模块标签选择器下载图片,以及正则匹配标签

标签选择器对象 HtmlXPathSelector()创建标签选择器对象,参数接收response回调的html对象需要导入模块:from scrapy.selector import HtmlXPathSelector select()标签选择器方法,是HtmlXPathSelector里的一个方法,参数接收选择器规则,返回列表元素是一个标签对象 extract()获取到选择器过滤后的内容,返回列表元素是内容 选择器规则 //x 表示向下查找n层指定标签,如://div 表示查找所有div标签

python实战——网络爬虫之request

Urllib库是python中的一个功能强大的,用于操做URL,并在做爬虫的时候经常要用到的库,在python2中,分为Urllib和Urllib2两个库,在python3之后就将两个库合并到Urllib库中,使用方法有所不同,我使用的是python3. 第一步,先导入Urllib库对应的模块,import urllib.request 或者直接导入request模块 from urllib import request from urllib import request file = req

爬虫学习 04.Python网络爬虫之requests模块(1)

爬虫学习 04.Python网络爬虫之requests模块(1) 引入 Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用. 警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症.冗余代码症.重新发明轮子症.啃文档症.抑郁.头疼.甚至死亡. 今日概要 基于requests的get请求 基于requests模块的post请求 基于requests模块ajax的get请求 基于requests模块ajax的post请求 综合项目练习:爬取国家药品监

爬虫1 爬虫介绍, requests模块, 代理(正向代理,反向代理), 爬梨视频, 自动登录网站, HTTP协议复习

HTTP协议复习 参考:https://www.cnblogs.com/an-wen/p/11180076.html 1爬虫介绍 # 1 本质:模拟发送http请求(requests)---->解析返回数据(re,bs4,lxml,json)--->入库(redis,mysql,mongodb) # 2 app爬虫:本质一模一样 # 3 为什么python做爬虫最好:包多,爬虫框架:scrapy:性能很高的爬虫框架,爬虫界的django,大而全(爬虫相关的东西都集成了) # 4 百度,谷歌,就