使用 selenium wire 获取浏览器运行时发出的请求

发表于:2022-5-31 09:47

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:diy01    来源:稀土掘金

  前言
  有的时候要获取网站的上显示一些信息,如招聘网站在招聘的公司需要的岗位,公司的名称,公司的地址,但一个个岗位点进去拿公司的地址,加载时间太长。
  通过抓包发现具体的信息在某一个ajax请求里面已经全返回出来了,在页面只显示了一小部分。或者某个网站登录之后需要某个token去调api。
  这个时候就可以使用selenium wire,直接拿取某个请求返回的数据,或传入的参数。
  1.环境要求
  ·Python 3.6 +
  · Selenium 3.4.0 +
  2.安装
  pip install selenium-wire
  
  3.示例
  from seleniumwire import webdriver
  driver = webdriver.Chrome()
  driver.get('https://www.baidu.com')
  # 通过requests属性访问请求
  for request in driver.requests:
      if request.response:
          print("Url:", request.url)
          print("Code:", request.response.status_code)
          print("Content-Type:", request.response.headers['Content-Type'])

  运行结果(前六条请求):


  4.拦截器
  可以在某些请求发出前,修改请求的参数或直接阻止请求。
  import json
  from seleniumwire import webdriver
  # 设置拦截器
  def interceptor(request):
      # 拦截.png,.jpg,.gif结尾的请求
      if request.path.endswith(('.png', '.jpg', '.gif')):
          request.abort()
  driver = webdriver.Chrome()
  driver.request_interceptor = interceptor
  driver.get('https://www.baidu.com')
  # 通过requests属性访问请求
  for request in driver.requests:
      if request.response:
          print("Url:", request.url)
          print("Code:", request.response.status_code)
          print("Content-Type:", request.response.headers['Content-Type'])

  运行结果(前六条请求):

  5.添加和修改请求参数
  # 设置拦截器
  def interceptor(request):
      # 添加请求参数
      params = request.params
      params['foo'] = 'bar'
      request.params = params
      # 修改POST请求正文中的JSON
      if request.method == 'POST' and request.headers['Content-Type'] == 'application/json':
          # 获取原请求内容
          body = request.body.decode('utf-8')
          data = json.loads(body)
          # 修改要改变的参数
          data['foo'] = 'bar'
          # 将修改好的参数设置回请求
          request.body = json.dumps(data).encode('utf-8')
          # 更新内容长度
          del request.headers['Content-Length']
          request.headers['Content-Length'] = str(len(request.body))

  本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号