【发布时间】:2015-12-07 08:06:22
【问题描述】:
我有一个带有多行复选框的 html 页面。我想找到表中的所有复选框并单击它。 请问我能做到这一点的最好方法是什么? 我的第一次尝试是通过 ID 识别出带有复选框的表
table_id = self.driver.find_element(By.ID, 'data_configuration_datamaps_ct_fields_body')
然后我得到所有的行
rows = table_id.find_elements(By.TAG_NAME, "tr")
然后我使用 for 循环遍历行。在每次迭代中,我都会找到该列
for row in rows:
col_name = row.find_elements(By.TAG_NAME, "td")[0]
然后我从列中找到复选框并单击它。
col_checkbox = col_name.find_elements(By.XPATH, "//input[@type='checkbox']")
col.checkbox.click()
我做错了。做这个的最好方式是什么? 我正在将 Selenium Webdriver 与 Python 一起使用
我的完整代码sn-p如下:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
def delete_all_datamaps(self):
try:
WebDriverWait(self.driver, 20).until(EC.presence_of_all_elements_located((By.TAG_NAME, 'td')))
table_id = self.driver.find_element(By.ID, 'data_configuration_datamaps_ct_fields_body')
rows = table_id.find_elements(By.TAG_NAME, "tr")
print "Rows length"
print len(rows)
for row in rows:
# Get the columns
col_name = row.find_elements(By.TAG_NAME, "td")[0] # This is the 1st column
print "col_name.text = "
print col_name.text
col_checkbox = col_name.find_elements(By.XPATH, "//input[@type='checkbox']")
col.checkbox.click()
except NoSuchElementException, e:
return False
return None
HTML 是:
<table id="data_configuration_datamaps_ct_fields_body" cellspacing="0" style="table-layout: fixed; width: 100%;">
<colgroup>
<tbody>
<tr class="GOFU2OVFG GOFU2OVMG" __gwt_subrow="0" __gwt_row="0">
<td class="GOFU2OVEG GOFU2OVGG GOFU2OVHG GOFU2OVNG">
<div __gwt_cell="cell-gwt-uid-185" style="outline-style:none;" tabindex="0">
<input type="checkbox" tabindex="-1"/>
</div>
</td>
<td class="GOFU2OVEG GOFU2OVGG GOFU2OVNG">
td class="GOFU2OVEG GOFU2OVGG GOFU2OVNG">
td class="GOFU2OVEG GOFU2OVGG GOFU2OVBH GOFU2OVNG">
</tr>
</tbody>
</table>
下面的 xpath 会找到第一个复选框
//table[@id="data_configuration_datamaps_ct_fields_body"]//tr/td/div/input
我只需要在这个表中找到复选框。
谢谢, 里亚兹
【问题讨论】:
-
问题到底是什么?它没有按您的预期工作吗?您收到错误消息吗?你想得到什么,你实际上得到了什么?目前还不清楚你的解释...
-
如果可能,请包含指向相关网络资源的链接。
-
您的复选框是否在相同的结构下?
-
是的,复选框的结构相同。它不是面向公众的 URL。 Web 应用程序安装在本地计算机上,只有客户端可以访问。
标签: python-2.7 selenium xpath selenium-webdriver webdriver