【问题标题】:How can I click button or div tag dynamically until it disappear from page using selenium python?如何使用 selenium python 动态单击按钮或 div 标签,直到它从页面中消失?
【发布时间】:2015-07-23 07:41:07
【问题描述】:

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

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

处于_read_status 提高 BadStatusLine(线) httplib.BadStatusLine: ''

带有 xpath 的示例代码

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']/div1/div[3]/div1/div /div/div[3]/div/div1/div 有没有办法获得我们自己的 xpath 而不是使用 firepath?

【问题讨论】:

    标签: python selenium xpath


    【解决方案1】:

    这是针对您的问题的 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");
    }
    

    【讨论】:

    • 感谢您的回复,我已经在 python 中开发了您的逻辑,但是如果我将它用于多个链接,它会引发异常 -in _read_status raise BadStatusLine(line) httplib.BadStatusLine: '' 或有时 消息:无法找到元素:{"method":"xpath","selector":"//div[@class=\"load-more\"]"}。知道为什么会这样吗?
    • 你可能没有注意到我的最后一个问题,如何为 .//*[@id='reviews-container']/div1/div[3]/div1 编写自己的评论 xpath /div/div/div[3]/div/div1/div ?
    • @Mukesh 我找不到你。 你可能没有注意到我的最后一个问题,问题是什么,它的链接在哪里?
    • 我在问我问题的最后一行,写自己的 xpath 的评论。现在我已经解决了。在为多个链接单击 load more 时,我仍然会遇到异常(在第一条评论中)?如何解决?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多