我有以下网站,我想点击等待 x 秒后弹出的“跳过此广告”按钮。
我的代码如下:
import selenium
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://festyy.com/wpixmC')
sleep(10)
driver.find_element_by_xpath('/html/body/div[3]/div[1]/span[5]').click()
但是,当我检查该元素时,我没有看到要单击的连接链接。另外,我得到
ElementClickInterceptedException: Message: element click intercepted: Element <span class="skip-btn
show" id="skip_button" style="cursor: pointer">...</span> is not clickable at point (765, 31). Other
element would receive the click: <div style="position: absolute; top: 0px; left: 0px; width: 869px;
height: 556px; z-index: 2147483647; pointer-events: auto;"></div>
不知何故,似乎一切都被重定向到更大的类?我怎样才能克服这个问题?当我尝试复制 xpath 时,我也只得到以下内容: /div
提前致谢
最佳答案
您收到的错误(“元素点击被拦截”)似乎是由于页面加载时放置了一个 div,它占据了整个页面,从而阻止 Selenium 单击跳过按钮.
因此,您必须先删除该 div,然后运行以下命令:
driver.find_element_by_xpath('/html/body/div[3]/div[1]/span[5]').click()
您可以通过运行一些 JavaScript 代码来删除 div,如下所示:
driver.execute_script("""
var badDivSelector = document.evaluate('/html/body/div[7]',
document.documentElement, null, XPathResult.FIRST_ORDERED_NODE_TYPE,
null);
if (badDivSelector) {
var badDiv = badDivSelector.singleNodeValue;
badDiv.parentNode.removeChild(badDiv);
}
""")
上面的代码找到整个页面 div(由 xpath 标识)并将其从页面中删除。
您的最终代码应如下所示:
import selenium
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome()
driver.get('http://festyy.com/wpixmC')
sleep(10)
driver.execute_script("""
var badDivSelector = document.evaluate('/html/body/div[7]',
document.documentElement, null, XPathResult.FIRST_ORDERED_NODE_TYPE,
null)
if (badDivSelector) {
var badDiv = badDivSelector.singleNodeValue;
badDiv.parentNode.removeChild(badDiv);
}
""")
driver.find_element_by_xpath('/html/body/div[3]/div[1]/span[5]').click()
....
关于python - 无法点击带有 Selenium 的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59672081/