【问题标题】:moving onto the next page using selenium by python通过 python 使用 selenium 进入下一页
【发布时间】:2020-12-24 14:26:00
【问题描述】:
url_main = "https://comic.naver.com/webtoon/detail.nhn?titleId=131385&no=292"

这个网页最后有cmets的分页。当我检查页面时,按钮编译如下:

<a href="#" class="u_cbox_page" data-action="page#move" data-log="RPC.pgnum"><span class="u_cbox_num_page">3</span></a>

我想点击这些按钮之一,所以我尝试了

driver = webdriver.Chrome(driver_path)
driver.get(url_main)
driver.switch_to.frame('commentIframe')
view_all_comments = driver.find_element_by_xpath('''//*[@id="cbox_module"]/div/div[8]/a''')
view_all_comments.click()
page_buttons = driver.find_elements_by_css_selector(".u_cbox_page")
page_buttons[2].click()

但它会返回

StaleElementReferenceException: stale element reference: element is not attached to the page document
  (Session info: chrome=87.0.4280.88)

我该如何解决这个问题?

【问题讨论】:

  • .u_cbox_page 只返回一个匹配项,你怎么能使用下标作为page_buttons[2]
  • 如果你从顶部执行代码到view_all_comments.click(),你会发现.u_cbox_page有10个匹配项。相当于最后点击了“전체 댓글 더보기”按钮。
  • 啊,我错过了那一步:/

标签: python html css selenium selenium-chromedriver


【解决方案1】:

使用 WebDriverWait element_to_be_clickable 等待第一个按钮可点击,然后使用 WebDriverWait visibility_of_all_elements_located 等待其他按钮出现,如下所示:

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(driver_path)
driver.get(url_main)
driver.switch_to.frame('commentIframe')
wait = WebDriverWait(driver, 10)
view_all_comments = wait.until(ec.element_to_be_clickable((By.XPATH, '''//*[@id="cbox_module"]/div/div[8]/a''')))
view_all_comments.click()
page_buttons = wait.until(ec.visibility_of_all_elements_located((By.CSS_SELECTOR,".u_cbox_page")))
page_buttons[2].click()

【讨论】:

  • 它返回TimeoutException,即使将等待时间延长到60s。该代码在您的计算机上工作正常吗?
  • 我编辑了答案:visibility_of_all_elements_located 在这种情况下比presence_of_all_elements_located 好。现在它可以正常工作了
  • 现在它工作正常,但它引发了另一个问题:每当我尝试单击另一个按钮时它会再次返回StaleElementReferenceException(例如,在执行page_buttons[3].click() 后执行page_buttons[2].click())。我可以通过在代码之间重新定义 page_buttons 来解决这个问题,但我想知道为什么我不能立即点击另一个按钮。
  • 因为 DOM 中的按钮发生了变化,所以需要重新定义 page_buttons 或者一次取一个按钮
猜你喜欢
  • 2017-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多