Skip to main content
 首页 » 编程设计

python之Selenium 驱动程序有时不会点击元素

2025年05月04日19www_RR

目前我正在编写一个可以在无限循环中工作的网络抓取工具。它获取一个页面,搜索一些按钮并单击其中一个。但有时它不会!我保存了一个屏幕截图以防万一,它显示我点击按钮后页面没有改变。

driver.find_element_by_xpath('//input[@name = "btn"]').click() 
time.sleep(3) 

我通过循环检查绕过了这个问题,我们是否仍然看到该元素。

while driver.find_elements_by_xpath('//input[@name = "Submit"]') != []: 
    driver.find_element_by_xpath('//input[@name = "Submit"]').click() 

但希望找到这个问题的根本原因。它可能是什么?

请您参考如下方法:

我的申请也遇到了类似的问题。通过 Action 类单击元素对我有用。 以下是 Java 中的示例代码:

WebElement webElement = driver.findElement(By.id("Your ID Here")); 
Actions builder = new Actions(driver); 
builder.moveToElement(webElement).click(webElement); 
builder.perform(); 

如果用action类点击不成功,你也可以尝试用Javascript点击元素。

WebElement webElement = driver.findElement(By.id("Your ID here")); 
JavascriptExecutor executor = (JavascriptExecutor) driver; 
executor.executeScript("arguments[0].click();", webElement);