• Python爬虫基础之Requests详解


    原文地址:https://program-park.top/2023/10/27/reptile_4/

    本文章中所有内容仅供学习交流使用,不用于其他任何目的,严禁用于商业用途和非法用途,否则由此产生的一切后果均与作者无关。

    1. 简介

      Requests 是用 Python 编写,基于 urllib,采用 Apache2 Licensed 开源协议认证的 HTTP 库。它支持 HTTP 连接保持和连接池、cookie 保持会话、文件上传、自动响应内容编码,以及国际化的 URL 和 POST 数据自动编码等,比 urllib 更加方便简洁,在日常开发中可以节约我们大量的时间。
      这是 Requests 官网的描述:

    2. 安装

      因为是第三方库,所以我们需要使用 pip 下载:

    pip install requests
    
    • 1

      使用时直接导入 requests 模块即可:

    import requests
    
    • 1

    3. 发送请求

      首先,我们先从最简单的 HTTP 请求开始,发送一个 GET 请求到指定的 URL,获取响应数据:

    import requests
    
    url = 'https://www.baidu.com/s'
    headers = {
        'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.102 Safari/537.36 Edg/104.0.1293.63'
    }
    data = {
        'wd': '北京'
    }
    response = requests.get(url = url, headers=headers, params=data)
    print(response.text)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

      除了发送 GET 请求,我们还可以发送其他类型的请求,例如 POST 请求:

    import requests
    
    url = 'http://fanyi.baidu.com/sug'
    headers = {
        'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.102 Safari/537.36 Edg/104.0.1293.63'
    }
    data = {
        'kv': 'eye'
    }
    response = requests.post(url=url, headers=headers, data=data)
    print(response.text)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

      这里需要注意的是,Get 请求的参数名字是params,Post 请求的参数名字是data
      我们正常在发送请求时,会带上一些请求参数,比如 params、data、json、files、timeout、headers、cookies 等等,下面是常用参数的具体说明:

    参数释义示例
    url请求的 URL 地址,必选参数url=http://program-park.top
    paramsurl 请求的参数(dict 字典),一般用于 get 请求,post 请求也可用params={‘key1’:‘value1’, ‘key2’:‘value2’}
    datapost 请求的参数,字典(dict) 或文件类对象(file-like object)data={‘key1’:‘value1’, ‘key2’:‘value2’}
    jsonpost 请求的 json 参数json={‘key1’:‘value1’, ‘key2’:‘value2’}
    filespost 请求文件流数据,字典上传files={‘file’:open(‘report.xls’, ‘rb’)} 或 files={‘file’: (‘report.xls’, open(‘report.xls’, ‘rb’), ‘application/vnd.ms-excel’, {‘Expires’:‘0’})}
    timeout请求响应的最长等待时间。默认 Nonetimeout=5
    headershttp 请求头(HTTP Headers)信息headers={‘user-agent’:‘my-app/0.0.1’}
    cookies字典 dict 或 cookie 对象cookie={‘cookie_are’:“working”}
    verify默认 True,为 False 时忽略对 SSL 证书的验证,还可以接收 SSL 证书的路径,为会话加载 SSL 证书。verify=False
    cert指定一个班底证书用作客户端证书,可以是单个文件或一个包含两个文件路径的元组,本地的私有 key 必须是解密状态cert=(‘/path/client.cert’, ‘/path/client.key’) 或 cert=(‘/path/client.pem’)
    authHTTP 验证信息from requests.auth import HTTPBasicAuth
    auth = HTTPBasicAuth()

      当然,Requests 支持的请求方式不只这两种:

    requests.post('')
    requests.put('')
    requests.delete('')
    requests.head('')
    requests.options('')
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4. 处理响应

      说完发送请求的相关知识点,下面就是接收到响应后如何做处理了,Requests 库提供了丰富的方法来处理响应数据:

    属性或方法说明
    apparent_encoding编码方式
    close()关闭与服务器的连接
    content返回响应的内容,以字节为单位
    cookies返回一个 CookieJar 对象,包含了从服务器发回的 cookie
    elapsed返回一个 timedelta 对象,包含了从发送请求到响应到达之间经过的时间量,可以用于测试响应速度。比如 r.elapsed.microseconds 表示响应到达需要多少微秒。
    encoding解码 r.text 的编码方式
    headers返回响应头,字典格式
    history返回包含请求历史的响应对象列表(url)
    is_permanent_redirect如果响应是永久重定向的 url,则返回 True,否则返回 False
    is_redirect如果响应被重定向,则返回 True,否则返回 False
    iter_content()迭代响应
    iter_lines()迭代响应的行
    json()返回结果的 JSON 对象 (结果需要以 JSON 格式编写的,否则会引发错误)
    links返回响应的解析头链接
    next返回重定向链中下一个请求的 PreparedRequest 对象
    ok检查 “status_code” 的值,如果小于400,则返回 True,如果不小于 400,则返回 False
    raise_for_status()如果发生错误,方法返回一个 HTTPError 对象
    reason响应状态的描述,比如 “Not Found” 或 “OK”
    request返回请求此响应的请求对象
    status_code返回 http 的状态码,比如 404 和 200(200 是 OK,404 是 Not Found)
    text返回响应的内容,unicode 类型数据
    url返回响应的 URL

      这里我就不做演示了,都是些很基础的方法,上手一试便知。

    5. IP代理

      Requests 基础的发送请求、处理响应说完之后,还需讲一下如何使用代理 IP 来发送请求,这个之前在 urllib 的教程中也说过,就直接上代码了,在快代理(https://www.kuaidaili.com/free/)白嫖个能用的代理做个示例:

    import requests
    
    url = 'http://www.baidu.com/s?'
    headers = {
        'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.102 Safari/537.36 Edg/104.0.1293.63'
    }
    data = {
        'wd': 'ip'
    }
    proxy = {
        'http': 'http://101.200.185.203:16816'
    }
    response = requests.get(url=url, headers=headers, params=data, proxies=proxy)
    content = response.text
    with open('daili.html', 'w', encoding='utf-8') as fp:
        fp.write(content)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    6. Cookie登录

      Cookie 是一种保存在电脑上的一种文件,当我们使用电脑进行浏览网页的时候,服务器就会生成一个证书,并且返回给我们的电脑,这个证书就是 Cookie,一般情况下,Cookie 是服务器写入客户端的文件,我们也可以叫浏览器缓存。
      一般情况下,网站是通过 Cookie 对请求进行保存,会根据用户进行特定的内容进行展示,也可以对密码进行存储,Cookie 文件是以浏览器为载体,并且有浏览器为支撑,我们可以在浏览器中设置阻止,这样的话,服务器就不能写进 Cookie,现在很多浏览器都是能支持 Cookie,不过有些时候,网站访问不支持 Cookie 的话,会出现浏览器不能访问的情况。
      这里结合登录古诗文网(https://www.gushiwen.cn/)的案例来讲解如何使用 Requests 实现 Cookie 登录。使用 Requests 处理 Cookie 有三种方法:

    • Cookie 字符串放在 headers 中;
    • Cookie 字典放在请求方法requests.get()中作为参数接收;
    • 使用 Requests 提供的 session() 方法。

      我这里就只讲解第三个方法,因为前两个都需要手动添加 Cookie,一般企业开发用不到。Requests 提供了一个叫session()的方法,来实现客户端和服务端的会话保持,会话保持主要作用是保存 Cookie,下次请求会带上上次的 Cookie,以及实现和服务端的长连接,加快请求速度。使用方法:

    session = requests.session()
    response = session.get(url,headers)
    
    • 1
    • 2

      那么话不多说,直接上案例代码:

    import requests
    
    # 古诗文官网的登录地址
    url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'
    headers = {
        'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.102 Safari/537.36 Edg/104.0.1293.63'
    }
    
    # 获取页面源码
    response = requests.get(url=url, headers=headers)
    content = response.text
    
    # 解析页面源码,获取__VIEWSTATE和__VIEWSTATEGENERATOR
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(content, 'lxml')
    
    # 获取__VIEWSTATE
    viewstate = soup.select('#__VIEWSTATE')[0].attrs.get('value')
    # 获取__VIEWSTATEGENERATOR
    viewstategenerator = soup.select('#__VIEWSTATEGENERATOR')[0].attrs.get('value')
    # 获取验证码图片
    code = soup.select('#imgCode')[0].attrs.get('src')
    code_url = 'https://so.gushiwen.cn' + code
    
    # 会话保持
    seeion = requests.session()
    # 验证码的url内容
    response_code = seeion.get(code_url)
    content_code = response_code.content
    
    with open('code.jpg', 'wb') as fp:
        fp.write(content_code)
    
    # 获取验证码后保存到本地,观察验证码后输入
    code_name = input('输入验证码:')
    
    # 点击登录
    url_post = 'https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx'
    data_post = {
        '__VIEWSTATE': viewstate,
        '__VIEWSTATEGENERATOR': viewstategenerator,
        'from': 'http://so.gushiwen.cn/user/collect.aspx',
        'email': 'lkm869666@126.com',
        'pwd': 'XXXXXX',
        'code': code_name,
        'denglu': '登录'
    }
    
    response_post = seeion.post(url=url, headers=headers, data=data_post)
    content_post = response_post.text
    
    with open('gushiwen.html', 'w', encoding='utf-8') as fp:
        fp.write(content_post)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54

      观察上面的案例可以发现,在登录过程中,有一个图片验证码需要输入,我们这里是将图片保存到本地,手动输入图片的验证码接着再登录。其实在实际的企业开发中,这一步也是需要我们自动化去完成的,一般都是结合一些第三方打码平台(一般都是收费的)来调用接口,自动输入验证码。比如超级鹰(https://www.chaojiying.com/),这里会有自己的开发文档,里面有各个语言的 Demo,这个我就不详细说了,官网都是傻瓜式教程。

    参考文献

      【1】https://requests.readthedocs.io/projects/cn/zh_CN/latest/
      【2】https://requests.readthedocs.io/projects/cn/zh_CN/latest/user/quickstart.html
      【3】https://cloud.tencent.com/developer/article/2345961
      【4】https://zhuanlan.zhihu.com/p/366457854
      【5】https://blog.csdn.net/ctrlthh/article/details/133820373
      【6】https://www.runoob.com/python3/python-requests.html
      【7】https://www.cnblogs.com/lanyinhao/p/9634742.html
      【8】https://zhuanlan.zhihu.com/p/137649301
      【9】https://zhuanlan.zhihu.com/p/33288426
      【10】https://www.bilibili.com/video/BV1Db4y1m7Ho?p=84
      【11】https://www.php.cn/faq/413706.html
      【12】https://blog.51cto.com/u_14691/6678457

  • 相关阅读:
    python time模块 时间戳 与 结构化时间
    微软成功抵御峰值高达2.4Tbps的DDoS攻击
    服务治理-Nacos
    67-Java面向对象三大特征之三:多态
    机器学习小知识--面试得一塌糊涂
    数据结构之队列
    如何从单体架构迁移到微服务架构:挑战和最佳实践
    【深度学习基础】模型文件介绍
    STM32 printf 重定向到CAN
    SpringBoot技术在商场应急管理中的创新应用
  • 原文地址:https://blog.csdn.net/weixin_44758876/article/details/133983622