爬虫之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字段
# 我们来模拟知乎搜索
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
    • 比如在浏览器中搜索时,因为浏览器不识别汉字,所以我们要进行转化

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
#登录github,然后从浏览器中获取cookies,以后就可以直接拿着cookie登录了,无需输入用户名密码
#用户名:egonlin 邮箱378533872@qq.com 密码lhf@123

import requests

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

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


print('378533872@qq.com' 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':'11111111@qq.com',
    '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属性
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:123@localhost: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:pass@host:port',
    'https': 'socks5://user:pass@host:port'
}
respone=requests.get('https://www.12306.cn',
                     proxies=proxies)

print(respone.status_code)
原文地址:https://www.cnblogs.com/DE_LIU/p/8269991.html