爬虫之requests模块的使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

爬虫之requests模块的使用

tomjoy   2019-12-31 我要评论

一、Ruquest模块基础

requests模块可以模拟浏览器发送多种请求方式

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.orghttps://img.qb5200.com/download-x/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')

二、基于GET请求

1.基本请求

import requests
response=requests.get('http:/https://img.qb5200.com/download-x/dig.chouti.com/')
print(response.text)

2.带参数的GET请求(params、headers)

import requests
# 请求方式
kwords = input('请输入关键字:>>>').strip()
  # 使用urlencode可以解析中文
url = "https://www.baidu.com/s?"
params = {'wd': kwords}
# 请求头
baidu_headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36 chrome-extension",
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
}
# 发送请求
response = requests.get(url,
                        params=params,
                        headers=baidu_headers,
                        )
print(response.status_code)  # 响应状态码
# print(response.text)   # 返回的html

# 保存数据
with open('search1.html', 'w', encoding='utf-8') as f:
    f.write(response.text)
    print('保存成功')

3.带参数的GET请求(cookies)

# 基于get请求携带参数cookies, 以访问GitHub邮箱示范

import requests

url = 'https://github.com/settings/emails'
cookies = {'user_session':"Osrktx19GnRnCYy0eVgixmEc637QGQDaZ7Upi30RI6uG-WWk"}
response = requests.get(url,cookies=cookies)  #github对请求头没有什么限制,我们无需定制user-agent,对于其他网站可能还需要定制
print("928990486@qq.com" in response.text)  # True

三、基于POST请求

1.get请求与post请求的区别

#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参数,用来存放请求体数据

2、发送post请求,模拟浏览器的登录行为

注意:

​  1、对于登录来说,应该输错用户名或密码然后分析抓包流程,如果输对了浏览器就跳转了,就没法分析了,抓不到包了,
​ 2、要做登录的时候一定记得要把cookie先清除;
  3、requests.session():中间的cookie都不用自己分析了,有用的没用的都给放进来了、
  4、response.cookie.get_dict() #获取cookie

'''
一 目标站点分析
    浏览器输入https://github.com/login
    然后输入错误的账号密码,抓包
    发现登录行为是post提交到:https://github.com/session
    而且请求头包含cookie
    而且请求体(form data)包含:
        commit: Sign in
        utf8: ✓
        authenticity_token: NG74Lb4wcJn/emTlJS/A71Wk2WJioAwqgelWqBvPoqe0aD8tWsn8r+088bFUCOv7FY+MI9JmOy+ojP3pisz35w==ga_id: 804200945.1577712060
        login: 928990486@qq.com
        password: 123456
        webauthn-support: supported
        webauthn-iuvpaa-support: unsupported
        required_field_55c0:
        timestamp: 1577713659056
        timestamp_secret: 65a511d2fd997e58b721ba390196372e6beb012c12a69d57156c9a2b20c267ea


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

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

import requests
import re


# 第一次请求
login_headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36 chrome-extension",
}

r1 = requests.get('https://github.com/login',headers=login_headers)

# 2)先解析获取authenticity_token与timestamp_secret, 通过re模块实现
authenticity_token=re.findall(r'<input type="hidden" name="authenticity_token" value="(.*?)" />',
                              r1.text,
                              re.S)[0]   # re.S 代表全文检索
timestamp_secret = re.findall('<input type="hidden" name="timestamp_secret" value="(.*?)" class="form-control" />',
                              r1.text,
                              re.S)[0]
print(authenticity_token)


# 第二次请求:带着初始cookie和TOKEN发送POST请求给登录页面,带上账号密码通过post请求访问https://github.com/session
form_data = {
        'commit': 'Sign in',
        'utf8': '✓',
        'authenticity_token':authenticity_token,
        'login': '928990486@qq.com',
        'password': 'qq7855993',
        'webauthn-support': 'supported',
        'webauthn-iuvpaa-support': 'unsupported',
        'required_field_55c0':'',
        'timestamp': 1577717454909,
        'timestamp_secret': timestamp_secret

}

r2 = requests.post('https://github.com/session',
                   data=form_data,
                   cookies=r1.cookies,
                   )
login_cookie = r2.cookies



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


print('928990486@qq.com' in r4.text) #True

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们