如何动态单击按钮或div标签,直到它使用selenium python从页面消失?

时间:2015-07-23 07:41:08

标签: python selenium xpath

使用this link我想要该页面的所有评论。 我已经使用xpath(在示例代码中给出)点击加载更多,直到它从该页面消失,但我的解决方案失败并发出以下错误。

错误消息:元素不再附加到DOM Stacktrace

_read_status中的

    提高BadStatusLine(线) httplib.BadStatusLine:''

带有xpaths的示例代码

Either 
driver.execute_script('$("div.load-more").click();')

or

xpath_content='//div[@class = "load-more"]' 
driver.find_element_by_xpath(xpath_content).click()

是否有任何解决方案在任何情况下都不会失败?如何点击加载直到它从该页面消失,或者是否有其他方式可以从此页面获取所有评论?

我正在使用firepath生成评论的xpath,这是 .//* [@ id ='reviews-container'] / div 1 / div [3] / div {{3 }} / DIV / DIV / DIV [3] / DIV / DIV 1 /格 有没有办法使用firepath来获取我们自己的xpath?

1 个答案:

答案 0 :(得分:0)

这是针对您的问题的java解决方案。你也可以使用相同的python逻辑

public static void loadAll(WebDriver driver) {
    while (true) {
        //Using findElements to get list of elements so that it wont throw exception if element is not present
        List<WebElement> elements = driver.findElements(By.xpath("//div[@class='load-more']"));
        //If the size is zero that means load more element is not present so breaking the loop
        if (elements.isEmpty()) {
            break;
        }
        //Assigning first element to a variable 
        WebElement loadEl = elements.get(0);
        //Getting text of element
        String text = loadEl.getText().toLowerCase();
         //check if text contains load more, as, if it is loading it will have ... ,so we cant click at that time
        if (text.contains("load more")) {
            loadEl.click();
        }
        //if text contains 1 to 4 means [for ex "Load More 4"] this is the last click so breaking the loop
        if (text.matches("load more [1-4]")) {
            break;
        }
    }
    System.out.println("Done");
}