我的刮刀在点击多个第一个链接时抛出错误

问题描述 投票:0回答:2

我已经在python中编写了一个与selenium结合使用的脚本,点击网页中a类下的domino-viewentry标签。我的脚本可以点击第一个a标签。但是,不是单击下一个,而是抛出错误。我的脚本和错误如下。我希望有人会看一看,并为我提供任何解决方案,以使其正确。

链接到网页:webpage_link

我的剧本:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get("above_link")

for item in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".domino-viewentry a"))):
    item.click()
    wait.until(EC.staleness_of(item))

driver.quit()

我遇到的错误:

line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Users\ar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 501, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\ar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "C:\Users\ar\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=63.0.3239.84)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 6.1.7601 SP1 x86)
python python-3.x selenium selenium-webdriver web-scraping
2个回答
1
投票

如果您只想单击页面上的所有链接以展开嵌入数据,则可以使用下面的代码

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get("http://www.siicex-caaarem.org.mx/Bases/TIGIE2007.nsf/4caa80bd19d9258006256b050078593c/")

while True:
    try:
        link = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[img[@src='/icons/expand.gif'] and not(./following::img[@src='/icons/collapse.gif'])]")))
        link.click()
        wait.until(EC.staleness_of(link))
    except:
        break

但是请注意页面是“不可扩展的”:一旦你到达01> 02> 0207,所有后面的链接都会消失,所以你无法继续......如果你需要实现更复杂的逻辑,请告诉我

更新

如果您只想点击“第一级”链接,可以尝试:

links_length = len(wait.until(EC.visibility_of_all_elements_located((By.XPATH, "//td[@colspan='9']//a[img]"))))

for index in range(links_length):
    driver.find_elements_by_xpath("//td[@colspan='9']//a[img]")[index].click()

0
投票

因此,当您单击第一个链接时,您将转到另一个页面,不幸的是,对第一页中其他元素的引用不再有效。每次加载页面时,您都必须重新查询DOM以查找元素。另见:http://www.seleniumhq.org/exceptions/stale_element_reference.jsp

为了您的目的,您可能最好抓住所有href,存储它们,并逐个访问它们来进行刮擦。

© www.soinside.com 2019 - 2024. All rights reserved.