如何在selenium Python中使用onclick查找元素?

2024-10-03 21:30:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我的HTML:

<tr>
            <td width="5%" align="center" height="25">&nbsp;1</td>
            <td width="20%" height="25">&nbsp;&nbsp;Mahamoodha Bi H</td>
            <td width="5%" align="center" height="25">&nbsp;356159</td>
            <td width="5%" align="center" height="25">&nbsp;Female</td>
            <td width="10%" align="center" height="25">&nbsp;32 Years</td>
            <td width="15%" align="center" height="25">&nbsp;22/09/2021 03:00 PM</td>
            <td width="15%" height="25">&nbsp;01/10/2021 03:53 PM</td>
            <td width="15%" height="25" align="center">&nbsp;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分别收集了这些

  1. 我能够使用下面的代码找到ID number元素,但我不知道如何使用它来单击行的最后一个元素

    selection = driver.find_element_by_xpath("//td[contains(text(),'{}')]".format(ID))
    
  2. 我得到了“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]

有没有更简单或更优雅的方法?这似乎很重复,效率也很低


Tags: thechildbytablefindwidthtrtd
2条回答

既然您已经提到要在这些行上进行迭代,请尝试一次如下操作:

获取高亮显示表中所有tr标记的定位器。并对其进行迭代以查找详细信息

xpath开头使用.查找元素中的元素

table = driver.find_elements_by_xpath("xpath for tr tags") # Should highlight all the `tr` tags

for row in table:
    id = row.find_element_by_xpath(".//td[3]").text # Assuming that the 3rd `td` tag contains the ID
    onclick = row.find_element_by_xpath(".//img").get_attribute("onclick") # Gets the value of onclick.

到达最后一列(最后一个列表元素)的一种方法如下:

selection = driver.find_elements_by_xpath("//td[contains(text(),'{}')]//parent::tr//td".format(ID))[-1]

使用这行代码,首先确定ID的位置,然后返回到trHTML元素,然后获取tr中的最后一个td

相关问题 更多 >