【发布时间】: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