我正在使用 Selenium、Python 和 PhantomJS 编写一个爬虫来使用 Google 的反向图像搜索。到目前为止,我已经成功上传图像并抓取第一页上的搜索结果。但是,当我尝试单击搜索结果导航时,我收到 StaleElementReferenceError。我在很多帖子中读到过它,但仍然无法实现该解决方案。这是中断的代码:
ele7 = browser.find_element_by_id("nav")
ele5 = ele7.find_elements_by_class_name("fl")
count = 0
for elem in ele5:
if count <= 2:
print str(elem.get_attribute("href"))
elem.click()
browser.implicitly_wait(20)
ele6 = browser.find_elements_by_class_name("rc")
for result in ele6:
f = result.find_elements_by_class_name("r")
for line in f:
link = line.find_elements_by_tag_name("a")[0].get_attribute("href")
links.append(link)
parsed_uri = urlparse(link)
domains.append('{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri))
count += 1
代码在 print str(elem.get_attribute("href"))
处中断。我该如何解决这个问题?
提前致谢。
最佳答案
点击链接将导致浏览器转到另一个页面;使对旧页面中元素的引用(ele5
、elem
)无效。
修改代码以不引用无效元素。
例如,您可以在访问其他页面之前获取网址:
ele7 = browser.find_element_by_id("nav")
ele5 = ele7.find_elements_by_class_name("fl")
urls = [elem.get_attribute('href') for elem in ele5] # <-----
browser.implicitly_wait(20)
for url in urls[:2]: # <------
print url
browser.get(url) # <------ used `browser.get` instead of `click`.
# ; using `element.click` will cause the error.
ele6 = browser.find_elements_by_class_name("rc")
for result in ele6:
f = result.find_elements_by_class_name("r")
for line in f:
link = line.find_elements_by_tag_name("a")[0].get_attribute("href")
links.append(link)
parsed_uri = urlparse(link)
domains.append('{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri))
关于python - StaleElementReferenceException selenium webdriver python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25957063/