我试图通过部分链接文本获取所有元素,然后单击它们,然后从下一页获取一些信息。 我的想法是,我应该单击每个链接,然后返回上一页,然后对其他链接重复该过程。我看到了这个帖子 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内-------------------------
答案 0 :(得分:1)
陈旧元素不可单击。这意味着您已导航到另一个页面。如果要再次单击所有这些链接,则可以返回该页面并重新加载列表。另一种方法是使用driver.get作为URL(您要单击的链接)
https://seleniumbyexamples.github.io/navget https://seleniumbyexamples.github.io/waitstateless