Javascript 为什么可以';在Chrome扩展中查找按钮(Python)

Javascript 为什么可以';在Chrome扩展中查找按钮(Python),javascript,python,html,google-chrome,selenium,Javascript,Python,Html,Google Chrome,Selenium,我正在使用含硒的BeautifulSoup。我正在用Selenium打开一个带有chrome扩展的网页。当我手动右键单击并“检查”按钮时,我可以看到html 查找电子邮件 如果我右键单击并“查看页面源代码”,这个html不会显示在源代码中,我想这就是selenium找不到它的原因。它似乎是由json和javascript驱动的,但我不确定它的全部工作原理。谁能建议我如何在这种环境中使用硒 以下是我打开浏览器的方式: options = webdriver.ChromeOptions()

我正在使用含硒的BeautifulSoup。我正在用Selenium打开一个带有chrome扩展的网页。当我手动右键单击并“检查”按钮时,我可以看到html

查找电子邮件

如果我右键单击并“查看页面源代码”,这个html不会显示在源代码中,我想这就是selenium找不到它的原因。它似乎是由json和javascript驱动的,但我不确定它的全部工作原理。谁能建议我如何在这种环境中使用硒

以下是我打开浏览器的方式:

    options = webdriver.ChromeOptions()
    options.add_argument("--start-maximized")
    options.add_extension('/home/henry/Downloads/candidate.ai-get-email,-salary,-social-link_v0.3.6.crx')
    with closing(Chrome(chrome_options=options)) as driver:
        driver.get(url)
下面是我尝试获取按钮的方式:

    button = driver.find_element_by_css_selector('btn')
    button.click()
下面是我得到的错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"btn"}

由于
btn
不是一个元素,而是一个
名称,因此您不能以自己的方式使用它。使用类名的一些可能方法有:

button = driver.find_element_by_css_selector('.btn')
button = driver.find_element_by_css_selector('button.btn')
button = driver.find_element_by_css_selector('button.btn.btn-primary')
button = driver.find_element_by_xpath('//button[@class="btn btn-primary"]')
...
您还可以通过其链接文本找到您的按钮:

button = driver.find_element_by_xpath('//button[.="Find Email"]')
button = driver.find_element_by_link_text("Find Email")
由于按钮位于
iframe
内,请使用以下代码:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver.switch_to_frame("bconsole")
button = WebDriverWait(driver, 2).until(EC.element_to_be_clickable((By.LINK_TEXT, "Find Email")))
...
# Perform required actions inside iframe
driver.switch_to_default_content()

您的选择器无效。一个有效的是:
button.btn
相同的错误:
selenium.common.exceptions.NoSuchElementException:Message:没有这样的元素:找不到元素:{“method”:“css selector”,“selector”:“button.btn”}
您似乎完全知道我在尝试做什么,但使用的是
button=driver.find\u element\u by\u css\u selector('button[)=“Find Email”]'
我得到以下信息
selenium.common.exceptions.InvalidSelectorException:Message:invalid selector:指定了无效或非法的选择器
button=driver.Find_element_by_css_selector('button[class=“btn btn primary”]))
给出
selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法定位元素:{“方法”:“css选择器”,“选择器”:“按钮[class=”btn btn primary“]”
@HenryM,哦,对不起,
css选择器
似乎不如
XPath
灵活。请检查更新的回答如果仍然存在异常,您可能需要使用
显式等待
来等待按钮出现,否则会倒霉。这些是错误,我已经进入了睡眠时间(5)确保页面已加载,并且我正在观察页面的加载情况,因此我知道页面已全部加载。
selenium.common.exceptions.NoSuchElementException:Message:没有此类元素:无法找到元素:{“方法”:“xpath”,“选择器”:”//button[@class=“btn btn primary”]}
selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“方法”:“xpath”,“选择器”:“//button[.=“查找电子邮件”]”}