我正在尝试在网络元素中找到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"> 87 </td>
<td class="main" align="center"> THS </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在整个页面源中查找,而不仅仅是当前元素。
您知道如何在当前元素中查找此标记吗?
答案 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。要从当前元素中搜索的运算符。
然后,您应该通过.text
和get_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")