在xpath中找到当前元素中的标签

时间:2015-11-27 09:09:09

标签: python selenium xpath

我正在尝试在网络元素中找到2个标签。我有href找到的这些元素的列表(包含“http://www.example.com/result=”)。

所以我有这个:

for elem in elements:
    # don't know what to type here

我想得到一个,在这种情况下('THS','http://www.example.com/result=1'

<tr bgcolor="FFF4FF">
    <td class="main" align="right">&nbsp;87&nbsp;</td>
    <td class="main" align="center">&nbsp;THS&nbsp;</td>
    <td class="main">
        <a href="http://www.example.com/result=1">xxx
        </a>
    </td>
</tr>

我试过这样做:

for elem in elements:
    shortcut = elem.find_element_by_xpath('//td[@align="center"]/text()')
    href = elem.find_element_by_xpath('//a[contains(@href,"http://www.example.com")]/@href')

但是有一个问题是Selenium在整个页面源中查找,而不仅仅是当前元素。

您知道如何在当前元素中查找此标记吗?

2 个答案:

答案 0 :(得分:1)

尝试relative xpath -

href = elem.find_element_by_xpath('//td[@align="center"]).find_element_by_xpath('.//a[contains(@href,"http://www.example.com")]').get_attribute('@href')

following轴 -

href = elem.find_element_by_xpath('//td[@align="center"]/following::a[contains(@href,"http://www.example.com")][1]').get_attribute('@href')

descendant

href = elem.find_element_by_xpath('//td[@align="center"]/descendant::a[contains(@href,"http://www.example.com")][1]').get_attribute('@href')

答案 1 :(得分:1)

首先,你需要通过&#34; .&#34;告诉Selenium。要从当前元素中搜索的运算符。

然后,您应该通过.textget_attribute("value")

提取值

//表示&#34;搜索整个网站&#34;

使用.//表示从当前元素搜索:

鉴于elements包含tr元素,您修改后的代码将为:

for elem in elements:
    shortcut = elem.find_element_by_xpath('.//td[@align="center"]').text
    href = elem.find_element_by_xpath('.//a[contains(@href,"http://www.example.com")]').get_attribute("href")