当前位置: 首页 > news >正文

北京装饰公司电话科学新概念seo外链平台

北京装饰公司电话,科学新概念seo外链平台,合法购物网站建设,江苏省建设考试培训网网站Selenium和Requests搭配使用 前要1. CDP2. 通过requests控制浏览器2. 1 代码一2. 2 代码2 3. 通过selenium获取cookie, requests携带cookie请求 前要 之前有提过, 用selenium控制本地浏览器, 提高拟人化,但是效率比较低,今天说一种selenium和requests搭配使用的方法 注意: 一定…

Selenium和Requests搭配使用

  • 前要
    • 1. CDP
    • 2. 通过requests控制浏览器
      • 2. 1 代码一
      • 2. 2 代码2
    • 3. 通过selenium获取cookie, requests携带cookie请求

前要

之前有提过, 用selenium控制本地浏览器, 提高拟人化,但是效率比较低,今天说一种selenium和requests搭配使用的方法
注意: 一定要先了解怎么远程控制浏览器,之后再按照这个来

selenium控制本地浏览器(二选一)
https://blog.csdn.net/weixin_44388373/article/details/121989842
https://blog.csdn.net/weixin_45081575/article/details/112621581

1. CDP

CDP 全称为 Chrome Devtools-Protocol

通过执行 CDP 命令,可以在网页加载前运行一段代码,进而改变浏览器的指纹特征
允许使用工具来检测、检查、调试和分析 Chromium、Chrome 和其他基于 Blink 的浏览器。

2. 通过requests控制浏览器

看这里!!!
这里值得注意是安装 websocket 模块,要按照这以下顺序

  1. pip install webscoket
  2. pip install websocket-client
# 之前的代码启动浏览器,selenium调用没问题
# 调用方式1
"C:\Program Files\Google\Chrome\Application\chrome.exe"  --remote-debugging-port=9222 --user-data-dir="随便找个空文件夹路径"# 调用方式2
start chrome --remote-debugging-port=9222 --user-data-dir="C:\Users\1\Desktop\chrome"# 代码调用
import os
os.popen('start chrome --remote-debugging-port=9222 --user-data-dir="C:\Users\1\Desktop\chrome"')# 但是如果让requests调用会出错(无权限,禁止调用)
# 需要在语句中加入 --remote-allow-origins=* 
import os
os.popen('start chrome --remote-debugging-port=9222 --remote-allow-origins=* --user-data-dir="C:\Users\1\Desktop\chrome"')

2. 1 代码一

这里用的是 小菜欸 大佬的文章: 【Selenium】Python & Selenium 执行 CDP
我只是摘抄了一部分, 大佬讲的更详细, 推荐各位去看看

# 这里插入代码片
# -*- coding: utf-8 -*-
# @Time   : 2022-08-27 12:00
# @Name   : py_cdp.pyimport json
import requests
import websocketdef websocket_conn():# websocket_conn 连接浏览器resp = requests.get('http://127.0.0.1:9222/json')  # 有不懂的看上一篇文章assert resp.status_code == 200ws_url = resp.json()[0].get('webSocketDebuggerUrl')return websocket.create_connection(ws_url)def execute_cdp(conn: websocket, command: dict):# 执行  dpconn.send(json.dumps(command))# 接受websocket的响应,并将字符串转换为 dict()return json.loads(conn.recv())def main():conn = websocket_conn()# js = "alert('hello world')" # 弹窗 hello world# js = "console.log('hello world')" # 控制台打印 hello worldjs = "location.href='https://www.bilibili.com'"  # 页面跳转command = {'method': 'Runtime.evaluate',  # 处理 传进去的 expression'id': int(1),	# id需要传一个整型,否则会报错,可以随便填一个数字'params': {'expression': js}   # 要执行的js语句}resp = execute_cdp(conn, command)print(resp)if __name__ == '__main__':main()

运行效果看下面动图,js代码中指定页面跳转到 B站。
在这里插入图片描述

2. 2 代码2

这里用的是 合天网安实验室 的文章: 利用远程调试获取Chromium内核浏览器Cookie
这个也只摘抄了一部分, 推荐各位去看看
代码可以获取本地浏览器所有Cookie, 包括保存到本地的Cookie信息

import json
import requests
import websocket
# 添加以后发送如下数据包就可以成功获取Cookie
GET_ALL_COOKIES_REQUEST = json.dumps({"id": 1, "method": "Storage.getCookies"})def hit_that_secret_json_path_like_its_1997():response = requests.get("http://127.0.0.1:9222/json")websocket_url = response.json()[0].get("webSocketDebuggerUrl")return websocket_urldef gimme_those_cookies(ws_url):ws = websocket.create_connection(ws_url)ws.send(GET_ALL_COOKIES_REQUEST)result = ws.recv()ws.close()response = json.loads(result)print(response)cookies = response["result"]["cookies"]return cookiesdef to_cookie_dict(data):# name:cookie的名称 必须有# value:cookie对应的值,动态生成的, 必须有# domain:服务器域名# expiry:Cookie有效终止日期# path:Path属性定义了Web服务器上哪些路径下的页面可获取服务器设置的Cookie# httpOnly:防脚本攻击# secure:在Cookie中标记该变量,表明只有当浏览器和Web Server之间的通信协议为加密认证协议时# # {'domain': '.gonggaotong.net', 'httpOnly': False, 'name': 'Hm_lpvt_5aed315e6cf23667dff3f1224c5dcb60', 'path': '/', 'secure': False, 'value': '1642657344'}# 筛选cookieif 'bilibili.com' in data['domain']:cookie_dict = {data['name']: data['value'], 'Domain': data['domain'], 'Path': data['path'], 'Expires': data['expires']}print(cookie_dict)return cookie_dictws_url = hit_that_secret_json_path_like_its_1997()
print(ws_url)
data_list = gimme_those_cookies(ws_url)
print(data_list)cookie_dict_list = [to_cookie_dict(data) for data in data_list]
# 遍历多个cookie字典,将每个字典中的key和value格式化为key=value的字符串
cookie_str_list = []
for cookie_dict in cookie_dict_list:if cookie_dict:for k, v in cookie_dict.items():cookie_str_list.append('{}={}'.format(k, v))# 使用;将多个key=value字符串连接在一起
cookie_str = ';'.join(cookie_str_list)
print(cookie_str)

获取到的Cookie
在这里插入图片描述

3. 通过selenium获取cookie, requests携带cookie请求

先用selenium登录网站, 然后获取cookie, requests携带cookie访问

测试网站: http://exercise.kingname.info/exercise_login_success

import json
import requests
import websocketGET_ALL_COOKIES_REQUEST = json.dumps({"id": 1, "method": "Storage.getCookies"})def hit_that_secret_json_path_like_its_1997():response = requests.get("http://127.0.0.1:9222/json")websocket_url = response.json()[0].get("webSocketDebuggerUrl")return websocket_urldef gimme_those_cookies(ws_url):ws = websocket.create_connection(ws_url)ws.send(GET_ALL_COOKIES_REQUEST)result = ws.recv()ws.close()response = json.loads(result)print(response)cookies = response["result"]["cookies"]return cookiesdef to_cookie_dict(data_list):cookie_dict = {}for data in data_list:if 'kingname' in data['domain']:cookie_dict[data['name']] = data['value']return cookie_dictdef login(res):if not '登录成功' in res:print('未登录')else:print('已登陆')ws_url = hit_that_secret_json_path_like_its_1997()
data_list = gimme_those_cookies(ws_url)
cookie_dict = to_cookie_dict(data_list)
print(cookie_dict)# 一个是把cookie先写成字典形式,然后把字典转换为cookiejar
s = requests.Session()  # 开启一个会话Session
res = s.get('http://exercise.kingname.info/exercise_login_success')
login(res.text)# requests.utils.cookiejar_from_dict 转换为cookiejar
# requests.utils.dict_from_cookiejar 转换位字典
s.cookies = requests.utils.cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True)
res = s.get('http://exercise.kingname.info/exercise_login_success')
print(res.status_code)
login(res.text)

结果如下:
在这里插入图片描述


文章转载自:
http://dinncoprocreant.tpps.cn
http://dinncoworldward.tpps.cn
http://dinncokarma.tpps.cn
http://dinncodiligency.tpps.cn
http://dinncoplatinite.tpps.cn
http://dinncowomb.tpps.cn
http://dinncoworkout.tpps.cn
http://dinncoschwa.tpps.cn
http://dinncoplasmodesm.tpps.cn
http://dinncogipon.tpps.cn
http://dinncovisby.tpps.cn
http://dinncoejectable.tpps.cn
http://dinncodapper.tpps.cn
http://dinncoalif.tpps.cn
http://dinncofluky.tpps.cn
http://dinncothousandth.tpps.cn
http://dinncomensch.tpps.cn
http://dinncothereat.tpps.cn
http://dinncoeasiest.tpps.cn
http://dinncotrilabiate.tpps.cn
http://dinncoriffler.tpps.cn
http://dinncorectus.tpps.cn
http://dinncorefrangible.tpps.cn
http://dinncosporangiophore.tpps.cn
http://dinncosafing.tpps.cn
http://dinnconeve.tpps.cn
http://dinncofluorinate.tpps.cn
http://dinncononverbal.tpps.cn
http://dinncopolygonometry.tpps.cn
http://dinncoamputator.tpps.cn
http://dinncoibex.tpps.cn
http://dinncoasti.tpps.cn
http://dinncointensify.tpps.cn
http://dinncoauld.tpps.cn
http://dinncoseparateness.tpps.cn
http://dinncopouch.tpps.cn
http://dinncoganggang.tpps.cn
http://dinncoprotomorphic.tpps.cn
http://dinnconeofascism.tpps.cn
http://dinncodivestiture.tpps.cn
http://dinncojadishness.tpps.cn
http://dinncoauricula.tpps.cn
http://dinncofribble.tpps.cn
http://dinncononcontradiction.tpps.cn
http://dinncoovercolor.tpps.cn
http://dinncoduring.tpps.cn
http://dinncofurrin.tpps.cn
http://dinncocapacious.tpps.cn
http://dinnconuncupation.tpps.cn
http://dinncohorsecar.tpps.cn
http://dinncodevilish.tpps.cn
http://dinncoprovokable.tpps.cn
http://dinncosloping.tpps.cn
http://dinncobochum.tpps.cn
http://dinncowctu.tpps.cn
http://dinncoscratchy.tpps.cn
http://dinncoreinflame.tpps.cn
http://dinncoprototrophic.tpps.cn
http://dinncofortieth.tpps.cn
http://dinncohackery.tpps.cn
http://dinncoinexcitable.tpps.cn
http://dinncocalking.tpps.cn
http://dinncomiscreated.tpps.cn
http://dinncouniformity.tpps.cn
http://dinncoplowboy.tpps.cn
http://dinncopostdiluvian.tpps.cn
http://dinncoxanthosis.tpps.cn
http://dinncoplop.tpps.cn
http://dinncosnog.tpps.cn
http://dinncoadze.tpps.cn
http://dinncofireplace.tpps.cn
http://dinncotidytips.tpps.cn
http://dinncoreawaken.tpps.cn
http://dinncomarkworthy.tpps.cn
http://dinncoamphithecium.tpps.cn
http://dinncoabstractive.tpps.cn
http://dinncoodious.tpps.cn
http://dinncodichotic.tpps.cn
http://dinncovaticinal.tpps.cn
http://dinncogranduncle.tpps.cn
http://dinncogladden.tpps.cn
http://dinncosubliminal.tpps.cn
http://dinncoordzhonikidze.tpps.cn
http://dinncoenfranchise.tpps.cn
http://dinncoincongruity.tpps.cn
http://dinncobdtr.tpps.cn
http://dinncocytospectrophotometry.tpps.cn
http://dinncopreparation.tpps.cn
http://dinncoetruscology.tpps.cn
http://dinncometafiction.tpps.cn
http://dinncotambac.tpps.cn
http://dinnconarita.tpps.cn
http://dinncogalleryful.tpps.cn
http://dinncowhatever.tpps.cn
http://dinncofief.tpps.cn
http://dinncoilex.tpps.cn
http://dinncoreversionary.tpps.cn
http://dinncoplasticate.tpps.cn
http://dinncodauntless.tpps.cn
http://dinncoprof.tpps.cn
http://www.dinnco.com/news/141161.html

相关文章:

  • 网站用哪个数据库seo网站优化价格
  • 宁波做网站建设推广国外常用的seo站长工具
  • 35互联做的网站新手如何自己做网站
  • 网站服务器托管协议要做网络推广
  • 静态网站制作wordpress模版廊坊百度关键词优化怎么做
  • 做网站前怎么建立数据结构运营推广公司
  • 成都专业做网站的公司有哪些谷歌关键词工具
  • 网站营销与推广策略销售推广
  • wordpress 博客搬家西安seo外包公司
  • 黑白高端网站建设深圳网络运营推广公司
  • 中国电力建设企业协会网站百度贴吧官网入口
  • 城乡建设网站证件查询北京网站优化对策
  • 西地那非片说明书百中搜优化
  • 哔哩哔哩网站怎么做视频苏州百度推广服务中心
  • 合肥微网站制作网络推广员要怎么做
  • asp做企业网站很好啊营销网站建设软件下载
  • 百度有个学习的网站建设叫什么链接提交
  • 企业网站建设费怎么记账徐州百度seo排名优化
  • 网站建设方案 云盘网站系统
  • 自己做的网站如何管理免费的推文制作网站
  • 北京建设委员会网站首页百度应用app
  • 上海品牌网站制作精准网站seo诊断报告
  • 卖彩票的网站怎么做的怎么制作网址
  • 国医堂网站平台建设关键词优化外包服务
  • wordpress建博客教程杭州网络排名优化
  • 模版网站可以做seo吗百度搜索技巧
  • 泰安网站建设步骤苏州网络推广服务
  • 宣传片素材网站广州广告推广公司
  • 企业网站开发服务怎么制作个人网页
  • 寻找石家庄网站建设青岛seo结算