【问题标题】:Python Selenium button click for cookiesPython Selenium 按钮点击获取 cookie
【发布时间】:2022-01-05 17:13:26
【问题描述】:

问题在于接受 cookie,我不确定为什么没有任何效果,尝试 By.CLASS, By.NAME 等接受 cookie "Sutinku su visais" 必须选择

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

PATH = Service("C:\\Program Files (x86)\\chromedriver.exe")
driver = webdriver.Chrome(service=PATH)

driver.get("https://www.telia.lt/privatiems")
driver.implicitly_wait(5)

link = driver.find_element(By.CLASS_NAME, "btn btn-primary js-cookie-modal-accept")
link.click()

不管我暂停/等待多长时间,始终是同一个问题:

 selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to 
 locate element

如果有人能教我如何根据不同的标准在 HTML 中找到我想要的按钮,我将不胜感激,因为我尝试过的已经无法实现任何目标。

我尝试在其中接受 cookie 的 HTML:

<div class="button-group button-group--pull-left" data-gtm-vis-has-fired-2746359_1882="1">
                <input class="btn btn-primary js-cookie-modal-accept" type="submit" value="Sutinku su visais" data-gtm-vis-has-fired-2746359_1882="1">
                <a class="btn btn-link js-cookie-modal-settings" data-gtm-vis-has-fired-2746359_1882="1">
                    Slapukų nustatymai
                </a>
            </div>

【问题讨论】:

    标签: python selenium cookies selenium-chromedriver


    【解决方案1】:

    Selenium CLASS_NAME中的类名不支持空格或多个空格

    请隐藏这个

    btn btn-primary js-cookie-modal-accept
    

    通过输入. 并删除空格,将其转换为CSS selcetor

    .btn.btn-primary.js-cookie-modal-accept
    

    所以你的有效代码块是:

    link = driver.find_element(By.CSS_SELECTOTR, ".btn.btn-primary.js-cookie-modal-accept")
    link.click()
    

    根据 OP 的要求,这是检查 HTML DOM 的一种方法

    检查步骤:

    Press F12 in Chrome -> 转到element 部分 -> 做一个CTRL + F -> 然后粘贴xpath 看看,如果你想要的element 用@ 得到高亮 987654332@匹配节点。

    我还建议您使用由 WebDriverWait 驱动的 ExplicitWait

    try:
        WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".btn.btn-primary.js-cookie-modal-accept"))).click()
    except:
        print("Could not click")
        pass
    

    进口:

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

    【讨论】:

    • 成功了,可能需要查找文档以获取更多信息。
    • 是的,最佳做法见上文。
    猜你喜欢
    • 2022-01-07
    • 2014-02-16
    • 2016-05-08
    • 2021-09-14
    • 2018-05-11
    • 1970-01-01
    • 2021-11-06
    相关资源
    最近更新 更多