簡體   English   中英

如何使用硒python動態單擊按鈕或div標簽直到其從頁面消失?

[英]How can I click button or div tag dynamically until it disappear from page using selenium python?

我想要使​​用此鏈接的所有評論。 我使用xpaths(在示例代碼中給出)單擊更多加載,直到它從該頁面消失為止,但是我的解決方案失敗並給出以下錯誤。

錯誤消息:元素不再附加到DOM Stacktrace

要么

在_read_status中引發BadStatusLine(line)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 1 / div / div / div [3] / div / div 1 / div是否有一種方法可以使用firepath來獲取自己的xpath?

這是針對您問題的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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM