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

标签 java selenium

我正在收集机器学习数据,并且正在努力抓取社交网络页面之一的数据。我一直很好,直到第 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/

相关文章:

java - 具有相同 GroupId 的多个 Kafka 监听器都接收消息

selenium - 如何通过 Spring Boot 使用新版本的库

Java Spring 投影内部投影

java - 切换 boolean 值,但只是一次? ( java )

java - 如何更快地从 Selenium WebElement 获取值?

javascript - 如何使用 Selenium 和 Node.JS 驱动 Firefox 滚动到元素?

php - 测试特定元素节点中的字符串

java - MacOS Catalina(v 10.15.3) : Error: “chromedriver” cannot be opened because the developer cannot be verified. 无法启动 Chrome 浏览器

Java程序以交互方式显示几何图形中的形状数量

java - Java 8's HashMap misbehaves if the keys implement Comparable in a way that isn' t 与equals一致是不是bug?