【问题标题】:Selenium how to click over elements stored in a listSelenium如何单击存储在列表中的元素
【发布时间】:2020-12-13 05:05:17
【问题描述】:

我试图通过部分链接文本获取所有元素,然后单击它们中的每一个并从以下页面获取一些信息。 我的想法是我应该单击每个链接,然后返回上一页,然后对其他链接重复该过程。我看到了这个帖子 Loop through Web Elements and Click each link

这是在java中,但是我不知道为什么点击后它没有返回上一页。

我收到“错误提示”

selenium.common.exceptions.StaleElementReferenceException:消息:过时的元素引用:元素未附加到页面文档 (会话信息:chrome=84.0.4147.89)

代码如下:

 links = driver.find_elements_by_partial_link_text("Preisvergleich")
    for i in range(len(links)):
        tmp = driver.find_elements_by_partial_link_text("Preisvergleich")
        if link[i].is_displayed():
            print(f"---------------- inside tmp {i} -------------------------")
            print(tmp[i])
            print(f"---------------- inside  Links {i} -------------------------")
            print(links[i])
            #tmp[i].click()
            links[i].click()

            html = driver.page_source
            response_obj = Selector(text=html)
                        
            des = response_obj.xpath("//p[@class='sh-ds__desc']/span/span/text()").get()
            name = response_obj.xpath("//*[@id='sg-product__pdp-container']/div/div[2]/div[1]/span/text()").get()
            tr_rows = response_obj.xpath("//table[@id='sh-osd__online-sellers-grid']/tbody/tr")
            
            for tr in tr_rows:
                result = result.append({             
                    'ean': EAN,
                    'name': name,
                    'price': remove_characters(tr.xpath("//div[@class='sh-osd__content']/table/tbody/tr[1]/td[2]/text()").get()),
                    'shipping': remove_characters(tr.xpath("//div[@class='sh-osd__content']/table/tbody/tr[2]/td[2]/text()").get()),
                    'endPrice': remove_characters(tr.xpath("//div[@class='sh-osd__content']/table/tbody/tr[4]/td[2]/text()").get()),
                    'seller': tr.xpath(".//td[1]/div/a/span[1]/text()").get(),
                    'desc': des}, ignore_index = True)
        
            driver.execute_script("window.history.go(-1)")

在这里您可以看到错误的原因。之后我定义了 tmp list 问题就解决了。我想知道有没有更清洁的想法来处理这个问题?

*---------------- 在 tmp 0 内 -------------------------

---------------- 在链接 0 内 -------------

---------------- 在 tmp 1 内 -------------

---------------- 在链接 1 中 -------------

*

【问题讨论】:

    标签: python selenium selenium-webdriver web-scraping


    【解决方案1】:

    陈旧的元素不可点击。这意味着您已导航到另一个页面。如果您想再次单击所有这些链接,您可以返回该页面并重新加载列表。另一种方法是使用 driver.get 作为 URL(您要单击的链接)

    https://seleniumbyexamples.github.io/navget https://seleniumbyexamples.github.io/waitstateless

    【讨论】:

      猜你喜欢
      • 2019-12-14
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      相关资源
      最近更新 更多