如何使用Xpath硒选择锚标记?

问题描述

我正在使用Selenium进行Web自动化,但是无法选择具有onClick属性且没有href和class Names的锚标记。下面是我要单击第一个和第三个锚标记的表单的源代码

<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>

有人可以建议我吗?

解决方法

这应该有效。使用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)