Python 通过xpath在当前元素中查找标记
我试图在一个web元素中找到2个标记。我有一个由Python 通过xpath在当前元素中查找标记,python,selenium,xpath,Python,Selenium,Xpath,我试图在一个web元素中找到2个标记。我有一个由href(包含“”)找到的这些元素的列表 所以我有这个: for elem in elements: # don't know what to type here 我想得到一个例子,在这种情况下,('THS','http://www.example.com/result=1“) 但是有一个问题是,Selenium在整个页面源代码中,而不仅仅是在当前元素中 您知道如何在当前元素中查找此标记吗 尝试相对xpath- href = elem.f
href
(包含“”)找到的这些元素的列表
所以我有这个:
for elem in elements:
# don't know what to type here
我想得到一个例子,在这种情况下,('THS','http://www.example.com/result=1“
)
但是有一个问题是,Selenium在整个页面源代码中,而不仅仅是在当前元素中
您知道如何在当前元素中查找此标记吗 尝试
相对xpath
-
href = elem.find_element_by_xpath('//td[@align="center"]).find_element_by_xpath('.//a[contains(@href,"http://www.example.com")]').get_attribute('@href')
或轴之后的
-
href = elem.find_element_by_xpath('//td[@align="center"]/following::a[contains(@href,"http://www.example.com")][1]').get_attribute('@href')
或子体
轴
href = elem.find_element_by_xpath('//td[@align="center"]/descendant::a[contains(@href,"http://www.example.com")][1]').get_attribute('@href')
尝试
相对xpath
-
href = elem.find_element_by_xpath('//td[@align="center"]).find_element_by_xpath('.//a[contains(@href,"http://www.example.com")]').get_attribute('@href')
或轴之后的
-
href = elem.find_element_by_xpath('//td[@align="center"]/following::a[contains(@href,"http://www.example.com")][1]').get_attribute('@href')
或子体
轴
href = elem.find_element_by_xpath('//td[@align="center"]/descendant::a[contains(@href,"http://www.example.com")][1]').get_attribute('@href')
首先,您需要通过“
”操作符告诉Selenium您要从当前元素中搜索
然后,您应该通过.text
和获取属性(“值”)
只是/
意思是“搜索整个网站”
使用/
意味着从当前元素搜索:
假设元素
包含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")
首先,您需要通过“
”操作符告诉Selenium您要从当前元素中搜索
然后,您应该通过.text
和获取属性(“值”)
只是/
意思是“搜索整个网站”
使用/
意味着从当前元素搜索:
假设元素
包含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")
非常感谢,这很有效。我只是好奇,为什么你改变了获取文本和href的方式。我以前也用同样的方法尝试过(/text()获取文本),它返回了一些异常,但我认为这是一种正确的语法。我错了吗?很高兴能帮上忙!find_元素返回一个node元素,xpath中的/text()不返回此类元素。此外…/@href不是有效的xpath表达式,因此在Python中没有get_text()方法,只有用于提取文本的.text。干杯,伙计!非常感谢,这很有效。我只是好奇,为什么你改变了获取文本和href的方式。我以前也用同样的方法尝试过(/text()获取文本),它返回了一些异常,但我认为这是一种正确的语法。我错了吗?很高兴能帮上忙!find_元素返回一个node元素,xpath中的/text()不返回此类元素。此外…/@href不是有效的xpath表达式,因此在Python中没有get_text()方法,只有用于提取文本的.text。干杯,伙计!