gpt4 book ai didi

java - Selenium Instagram 关注者抛出陈旧元素引用

转载 作者:行者123 更新时间:2023-12-01 17:19:18 25 4
gpt4 key购买 nike

我正在收集机器学习数据,并且正在努力抓取社交网络页面之一的数据。我一直很好,直到第 12 个追随者,然后就崩溃了。

方法 driver.findElement(By.xpath... 在第 13 个元素上停止工作,即使它正在滚动。任何人都可以指出它不可见的原因吗?这就是我到目前为止所想到的:

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Testing {

public static ChromeOptions options;
public static WebDriver driver;

public static void setup() {
System.setProperty("webdriver.chrome.driver", "resources/Drivers/chromedriver.exe");
options = new ChromeOptions();
driver = new ChromeDriver(options);
driver.get("https://www.instagram.com/accounts/login/");
}

public static void login() throws Exception {
String name = "xxxxxx";
String password = "xxxxxxx";
Thread.sleep(2000);
driver.findElement(By.name("username")).sendKeys(name);
driver.findElement(By.name("password")).sendKeys(password);
driver.findElement(By.tagName("form")).click();
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText("See All")));
driver.get(String.format("https://www.instagram.com/officialrickastley/"));
driver.findElement(By.partialLinkText("follower")).click();
try {
Thread.sleep(3000);
for (int j = 1; j < 1000; j += 11) {
System.out.println("j " + j);
WebElement element = driver.findElement(By.xpath(("/html/body/div[4]/div/div[2]/ul/div/li[" + (j) + "]/div/div[2]/div[1]/div/div/a")));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();
for (int i = 1; i < 12; i++) {
System.out.println("user: " + i + " " + driver.findElement(By.xpath(("/html/body/div[4]/div/div[2]/ul/div/li[" + (i + j) + "]/div/div[2]/div[1]/div/div/a")))
.getAttribute("title"));
Thread.sleep(300);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.close();
}
}
}

最佳答案

请尝试添加显式等待,直到元素可见,然后执行所需的操作。

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("ur xpath here")));

关于java - Selenium Instagram 关注者抛出陈旧元素引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61326951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com