Noob在这里: 我有一个小脚本从用户Ebay产品列表中收集所有产品链接,然后逐个打开它们。 它正确填充列表,它按预期打开第一个链接,等待一点然后返回上一页(产品列表)。
当尝试打开列表中的下一个链接时,它会崩溃,因为尽管列表仍包含相同数量的元素,但内容已更改:它不会保留任何链接。
我已经尝试过调试,试图通过使列表全局(IMO多余)来带来更多的持久性,但一切都无济于事。我已经检查过,并没有注意到有类似问题的人。
from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(30)
driver.maximize_window()
# navigate to the application home page
driver.get("http://www.ebay.de/sch/living_food/m.html/")
# populate with the list of product links
global link_name
link_name=driver.find_elements_by_xpath(".//[@id='ListViewInner']/li/h3/a")
def list_review():
print "Found " + str(len(link_name)) + " products:"
for link in link_name:
print link.text
linkproduct= link.get_attribute('href')
print linkproduct
print
def open_product(link):
print "Now testing: " + link.text
linkproduct = link.get_attribute('href')
print "with the link: " + linkproduct
link.click()
# driver.get(linkproduct)
print "wait 2 seconds"
driver.implicitly_wait(2)
print "return to product list and perform a little health check"
driver.back()
print "The list has " + str(len(link_name)) + " elements"
list_review()
print "Let's open the links one by one"
for link in link_name:
open_product(link)
print "We are back! Time for a list check! Still " + str(len(link_name)) + " elements"
print "I've just done: " + link.text
print
driver.quit()
答案 0 :(得分:0)
当您离开当前页面时,或者即使DOM被刷新,driver
"损失"网页元素,你得到StaleElementReferenceException
。
要迭代多个页面,您需要在每次迭代时重新定位列表,并且可以使用索引将您的位置保留在列表中
links_len = len(driver.find_elements_by_xpath(".//[@id='ListViewInner']/li/h3/a"))
for i in range(links_len):
link_name = driver.find_elements_by_xpath(".//[@id='ListViewInner']/li/h3/a")
open_product(link_name[i])
print "We are back! Time for a list check! Still " + str(len(links_len)) + " elements"
print "I've just done: " + link_name[i].text