python selenium:无法找到元素(输入 table)

python selenium : impossible to find element (input in a table)

我已经尝试了很多方法来查找该元素,但检索到的元素为我提供了一个空列表。 这是页面: https://www.avocatparis.org/annuaire 我尝试找到“nom”输入表单。 当我复制 xpath 时,我得到

//*[@id="_ctl0_Corps_txtRSNom"]

当我复制完整的 xpath 时,我得到

/html/body/form/table/tbody/tr/td[2]/table/tbody/tr[2]/td/table/tbody/tr/td/div/div/div[2]/table/tbody/tr[1]/td[2]/input

当我将其放入我的代码时:

input = self.driver.find_elements(by=By.XPATH,value='//*[@id="_ctl0_Corps_txtRSNom"]')

我得到一个空列表。

我是不是漏掉了什么?

谢谢。

所需的元素在 <iframe> 内,因此您必须使用 WebDriverWait 等待 iframe 可用,然后切换到它。然后你可以使用通常的 find_elements 命令获取元素。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver.get('https://www.avocatparis.org/annuaire')
WebDriverWait(driver, 30).until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, "iframe")))
element = driver.find_elements(By.XPATH, '//*[@id="_ctl0_Corps_txtRSNom"]')
print(len(element))

你会看到印刷品是 1


这不是真正的答案,因为它没有解决问题,但是它太长了,无法写在评论中。

通过检查 selenium 下载的 HTML 的文本版本(见下文),结果发现它缺少很多您通过手动打开检查器工具找到的 HTML浏览器。特别是包含您感兴趣的元素的 table,即 #Table4,不包含在 selenium 页面源中。我猜这是与某些 javascript 未加载有关的问题。我用 chrome 和 firefox 都试过了。

查看selenium页面源码运行

print(driver.page_source)

然后搜索<table(CTRL+F)你会看到只有5个结果,都是和CookiebotDialog相关的。相反,如果您进入浏览器检查器工具并搜索 //table,您将看到 11 个结果。

如果我找到让selenium下载完整HTML代码的方法,我会更新答案。

来自 selenium 文档

WebDriver Get the source of the last loaded page. If the page has been modified after loading (for example, by Javascript) there is no guarantee that the returned text is that of the modified page. Please consult the documentation of the particular driver being used to determine whether the returned text reflects the current state of the page or the text last sent by the web server.