我尝试使用 Selenium 单击一个在页面上加载更多新闻的按钮,但最终我总是遇到
org.openqa.selenium.ElementClickInterceptedException
或 org.openqa.selenium.TimeoutException
。我觉得我对前端的了解还不够,不确定是代码的问题还是站点保护机制的问题。我已经设法使用 Selenium 输入一篇新闻文章,但我永远无法向下滚动到按钮或识别它。有人可以帮我解答疑惑吗?
代码:
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class Main {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\ChromeD\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.infomoney.com.br/mercados/");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30)); // Maximum wait time of 30 seconds
wait.until((ExpectedCondition<Boolean>) wd ->
((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete"));
// Locate the "Load more" button
WebElement loadMoreButton = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//button[contains(@class, 'text-white') and contains(@class, 'bg-wl-neutral-950')]")));
// Scroll to the button using JavaScript
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);", loadMoreButton);
loadMoreButton.click();
}
}
我尝试过滚动并进行各种操作,例如强制 Selenium 等待一定时间直到页面加载,但没有成功。
看来问题出在Webelement上。 你能试试这个吗:
WebElement loadMoreButton=(//按钮[@data-ds-variant='二级'])[2]
JavascriptExecutor js = (JavascriptExecutor) 驱动程序; js.executeScript("arguments[0].scrollIntoView(true);", loadMoreButton);
loadMoreButton.click();