【发布时间】:2021-11-26 19:25:57
【问题描述】:
我的 HTML:
<tr>
<td width="5%" align="center" height="25"> 1</td>
<td width="20%" height="25"> Mahamoodha Bi H</td>
<td width="5%" align="center" height="25"> 356159</td>
<td width="5%" align="center" height="25"> Female</td>
<td width="10%" align="center" height="25"> 32 Years</td>
<td width="15%" align="center" height="25"> 22/09/2021 03:00 PM</td>
<td width="15%" height="25"> 01/10/2021 03:53 PM</td>
<td width="15%" height="25" align="center"> 01/10/2021 12:14 PM</td>
<td width="5%" height="25" align="center">
<img class="imgButtonStyle" src="../../images/continue.png" onclick="loadDischargeSummaryListDetails('3163','356159',1);" width="20" height="20">
</td>
</tr>
我有一个像上面那样的行列表。我需要遍历行并单击每行的最后一列以获取我需要的数据并关闭它们。我是 python 和 selenium 的新手,不知道该怎么做。
唯一唯一的数据是第三列中的数据,即ID号和最后一列“img”标签中的“onclick”值。其他数据在每一行或某些行中重复。
我用 beautifulsoup 分别收集了这些。
-
我可以使用下面的代码找到 ID 号元素,但我不知道如何使用它来单击行的最后一个元素。
selection = driver.find_element_by_xpath("//td[contains(text(),'{}')]".format(ID)) -
我得到了“onclick”值,但我不知道如何使用该值搜索可点击元素。我尝试了下面的代码,但它引发了“InvalidSelectorException”错误。
selection = driver.find_element_by_xpath("//img[@onclick=\"{}\")]".format(onclick))
我卡在这里,不知道如何选择和单击元素。
我用下面的代码解决了:
#Select the table
tab = driver.find_element_by_css_selector('#ipDischargeView > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2) > table:nth-child(1)')
#Find the total number of rows containing the imgButtonStyle
raw_list = len(tab.find_elements_by_class_name('imgButtonStyle'))
for n in range(0,raw_list):
#freshly search the page each iteration for the same table
tab = driver.find_element_by_css_selector('#ipDischargeView > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2) > table:nth-child(1)')
#Select the particular row from the list
patient = tab.find_elements_by_class_name('imgButtonStyle')[n]
有没有更简单或优雅的方法来做到这一点?这似乎相当重复和低效
【问题讨论】:
-
我觉得这篇文章可以帮到你:find-and-click-an-item-from-onclick-partial-value
标签: python selenium xpath onclick