【问题标题】:Capture elements with Selenium which are loaded lazy in Python使用 Selenium 捕获在 Python 中延迟加载的元素
【发布时间】:2022-01-19 10:41:58
【问题描述】:

尝试单击带有Selenium 的按钮,但我不断收到错误消息:

NoSuchElementException:消息:没有这样的元素:无法定位 元素:{“方法”:“链接文本”,“选择器”:“同意”}

这是我要点击的按钮。

我假设,弹出窗口是延迟加载的。我找到了一些来源,但无法使其工作。这是我的代码

import pandas as pd
import bs4
import selenium as sel
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
import time
import os

driver = sel.webdriver.Chrome() #uses Chrome driver in usr/bin/ from https://chromedriver.chromium.org/downloads
url = 'https://fbref.com/en/squads/0cdc4311/Augsburg'
driver.get(url)
time.sleep(5)
html = driver.page_source
soup = bs4.BeautifulSoup(html, 'html.parser')

#click button -> accept cookies
element = driver.find_element(By.LINK_TEXT, "AGREE")
element.click()

>>> NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"AGREE"}

我也试过

[...]
driver = sel.webdriver.Chrome() #uses Chrome driver in usr/bin/ from https://chromedriver.chromium.org/downloads
driver.implicitly_wait(10) # seconds'
[...]

并且弹出窗口确实存在。但仍然得到同样的错误。

【问题讨论】:

  • 我看那里没有接受 cookies 元素。
  • Mhhh,可能是一些地理特定问题要重现?我添加了屏幕截图和缺少的代码行。

标签: python selenium web-scraping


【解决方案1】:

会发生什么?

您尝试通过.LINK_TEXT, "AGREE" 选择<button>,这是行不通的,因为它是<button> 而不是链接。

如何解决?

等待xpath选择的<button>可点击:

#click button -> accept cookies
element = WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, '//button[text()="AGREE"]')))
element.click()

【讨论】:

  • 几分钟前发现的。不过还是谢谢。
  • 你能再帮我一次吗?如果我这样做element = driver.find_element(By.XPATH, '//button[text()="Get table as CSV (for Excel)"]')element.click() 我会得到Message: element not interactable
  • 当然,SO 很乐意帮助您解决这个问题,但要保持问题/答案的清洁 - 这将注定要为 asking a new question 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-23
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 2023-03-10
  • 1970-01-01
  • 2017-01-01
相关资源
最近更新 更多