使用Selenium (Python)从iFrame中提取cookie



我可以从网站获得cookie。但我对聊天机器人使用的cookie很感兴趣例如聊天机器人网站有:<www.kinguin.net><www.multibankfx.com><coschedule.com>

如果我们进入这些网站并"检查元素"他们,然后在cookie下看到secure. livchat .inc(这是聊天机器人)将有1或2个cookie如下图所示

在这张图片中,我正在查看聊天机器人的cookie在一个名为我们可以看到一个cookie,也就是"__livechat">

所以这个cookie就是我想用selenium自动提取的。

我的以下代码返回网站上的所有cookie,但"_livechat"缺少

import os, sys, json, codecs, subprocess, requests, time, string
from selenium import webdriver  
from selenium.webdriver.common.keys import Keys  
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup as bs
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Chrome()
host = 'kinguin.net'
driver.get("https://"+host)
cookies = driver.get_cookies()
driver.switch_to.default_content()
cookies = driver.get_cookies()
for item in cookies:
print(item['name'])

更进一步,我下面的代码进入聊天机器人的iFrame并获得cookie,但返回null

driver.switch_to.default_content()
elementID = driver.find_element_by_id('chat-widget')
driver.switch_to.frame(0)
cookies = driver.get_cookies()
for item in cookies:
print(item['name'])

@ble非常感谢-你建议的方式只对这个特定的网站有帮助,这不是我想要的。我很抱歉,如果我不能在我之前的查询中清楚地解释它,但我想要一个大规模网站数据集的通用解决方案。

例如,如果我们查看这里的聊天机器人是不同的,因此我将搜索它elementID = driver.find_element_by_id('hubspot-messages-iframe-container')

如果我在这之后使用你的代码driver.switch_to.frame(elementID)

它给出了错误

NoSuchFrameException: Message: no such frame: element is not a frame

使用这行代码,您可以找到iframe元素:

elementID = driver.find_element_by_id('chat-widget')

使用这个来切换到那个iframe,你就可以用你写的代码收集cookie了

driver.switch_to.frame(elementID)

完成后,用

切换到默认内容
driver.switch_to.default_content()

该页上有更多的iframe。最简单的方法是使用唯一标识符来查找元素,例如"id"或"name",并将其存储在变量中。"elementID"。我建议将其重命名为"iframe_element",因为它不是ID,您只是通过ID获得元素。此外,如果页面上没有那么多iframe (https://www.guru99.com/handling-iframes-selenium.html)

,则避免通过索引(driver.switch_to.frame(0))进行搜索。

最新更新