Selenium WebDriver find_elements方法找不到空元素



我将Selenium WebDriver与python和ChromeDriver一起使用。

当试图在thead中查找th元素时,find_elements方法只找到其中的3个,而DOM中有4个。其中一个没有找到,原来是一个空元素:

<table>
<thead>
<tr>
<th class="data-table-selection-icon" scope="col"></th>
<th scope="col">
<div class="bx--table-header-label">Whatever</div>
</th>
<th scope="col">
<div class="bx--table-header-label">Whatever2</div>
</th>
<th scope="col">
<div class="bx--table-header-label">Whatever3</div>
</th>
</tr>
</thead>
<tbody >
<tr>
<td width="16">
<svg><!-- some svg --></svg>
</td>
<td>Whatever</td>
<td>Whatever2</td>
<td>Whatever3</td>
</tr>
</tbody>
</table>

我使用了以下find_elements调用:

tr = thead.find_element_by_tag_name("tr")
table_headers = tr.find_elements_by_tag_name("th")  
table_headers2 = tr.find_elements(By.TAG_NAME,"th")  
table_headers3 = tr.find_elements(By.XPATH,"//th")  
table_headers4 = tr.find_elements(By.XPATH,"//node()[contains(@scope,'col')]")  
table_headers5 = driver.find_elements_by_xpath("//thead/tr/*")

他们都只找到了3个元素。

编辑:还有一件事:

硒4.3.0

  • 弃用的find_element_by_*和find_elements_by_*现在已删除(#10712(

不确定这有多犹太,但让我们试一试:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.relative_locator import locate_with
import pandas as pd
import time as t
chrome_options = Options()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--headless")

webdriver_service = Service("chromedriver/chromedriver") ## path to where you saved chromedriver binary
browser = webdriver.Chrome(service=webdriver_service, options=chrome_options)
url = 'https://stackoverflow.com/questions/73068196/selenium-webdriver-find-elements-methods-dont-find-empty-elements#73068196'
browser.get(url)
button = browser.find_element(By.XPATH, "//*[contains(text(), 'Run code snippet')]")
button.click()
iframe = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, "//iframe[@name='sif2']")))
browser.switch_to.frame(iframe)
t.sleep(1)
# table_head = browser.find_element(By.TAG_NAME, "thead").get_attribute("outerHTML")
table_head = browser.find_element(By.TAG_NAME, "thead")
th_cells = table_head.find_elements(By.TAG_NAME, "th")
for x in range(len(th_cells)):
print('th:', x, th_cells[x].get_attribute("outerHTML"))
browser.quit()

这返回4个元素:

th: 0 <th class="data-table-selection-icon" scope="col"></th>
th: 1 <th scope="col">
<div class="bx--table-header-label">Whatever</div>
</th>
th: 2 <th scope="col">
<div class="bx--table-header-label">Whatever2</div>
</th>
th: 3 <th scope="col">
<div class="bx--table-header-label">Whatever3</div>
</th>

所以。。您的原始表必须不同,否则我在您的代码中遗漏了一些内容。

最新更新