如何使用Xpath for selenium选择锚定标记?

2024-05-16 09:38:00 发布

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

我正在使用Selenium实现web自动化,但无法选择具有onClick属性且没有href和类名的锚标记。下面是表单的源代码,我想在其中单击第一个和第三个锚定标记

<td colspan="4" class="leftTopFormLabel">
    12. Details of Nominee :<span class="mandatoryField">*</span>
</td>
<td colspan="2" class="lastFormValue">
    <a onclick="openWin('NomineeDetails.aspx','','dialogWidth:1000px; dialogHeight:800px; center:yes')"
        style="text-decoration: Dynamic; color: Blue; cursor: pointer">Enter Details Here</a>
</td>
</tr>
<tr class="lastData_Section" id="Tr12">
<td colspan="4" class="leftTopFormLabel">
    13. Family Particulars of Insured Person:
</td>
<td colspan="2" class="lastFormValue">
    <a onclick="openWin('FamilyDetails_New.aspx','','dialogWidth:1000px; dialogHeight:800px; center:yes');"
        target="_blank" style="text-decoration: Dynamic; color: Blue; cursor: pointer">Enter
        Details Here</a>
</td>
</tr>
<tr class="lastData_Section" id="Tr18">
<td colspan="4" class="leftTopFormLabel">
    14. Details of Bank Accounts of Insured Person:<span class="mandatoryField">*</span>
</td>
<td colspan="2" class="lastFormValue">
    <a onclick="openWin('EmployeeBankDetails.aspx','','dialogWidth:1000px; dialogHeight:800px; center:yes');"
        style="text-decoration: Dynamic; color: Blue; cursor: pointer">Enter Details Here</a>
</td>
</tr>

有人能推荐我吗


Tags: ofdetailstrclasstdcenterspanonclick
2条回答

这应该行得通。使用contains方法分析onclick属性:

//a[contains(@onclick,'NomineeDetails.aspx')]

没有任何<a>...</a>元素具有href属性。它们都没有class属性

这里有一种方法可以选择那些具有onclick属性但没有target属性的对象

from bs4 import BeautifulSoup

data = '''\
<td colspan="4" class="leftTopFormLabel">
    12. Details of Nominee :<span class="mandatoryField">*</span>
</td>
<td colspan="2" class="lastFormValue">
    <a onclick="openWin('NomineeDetails.aspx','','dialogWidth:1000px; dialogHeight:800px; center:yes')"
        style="text-decoration: Dynamic; color: Blue; cursor: pointer">Enter Details Here</a>
</td>
</tr>
<tr class="lastData_Section" id="Tr12">
<td colspan="4" class="leftTopFormLabel">
    13. Family Particulars of Insured Person:
</td>
<td colspan="2" class="lastFormValue">
    <a onclick="openWin('FamilyDetails_New.aspx','','dialogWidth:1000px; dialogHeight:800px; center:yes');"
        target="_blank" style="text-decoration: Dynamic; color: Blue; cursor: pointer">Enter
        Details Here</a>
</td>
</tr>
<tr class="lastData_Section" id="Tr18">
<td colspan="4" class="leftTopFormLabel">
    14. Details of Bank Accounts of Insured Person:<span class="mandatoryField">*</span>
</td>
<td colspan="2" class="lastFormValue">
    <a onclick="openWin('EmployeeBankDetails.aspx','','dialogWidth:1000px; dialogHeight:800px; center:yes');"
        style="text-decoration: Dynamic; color: Blue; cursor: pointer">Enter Details Here</a>
</td>
</tr>
'''

soup = BeautifulSoup(data, "html.parser")

matches = soup.select("a[onclick]:not([target])")
for a in matches:
    print(a.attrs.keys(), a.text)

相关问题 更多 >