我有一些基本的selenium代码和一个表现良好的xpath表达式。
xpath:
/html/body/div/div/table[2]/tbody/tr/td/div/table/tbody/tr//td/div[5]/table/tbody/tr[2]
选择我感兴趣的部分,其中包含许多
元素。
然而,追加' // p'像这样:
/html/body/div/div/table[2]/tbody/tr/td/div/table/tbody/tr//td/div[5]/table/tbody/tr[2]//p
不会只选择那些
元素。相反,我最终得到的只是一个元素。
我显然遗漏了一些基本的东西。这是我的代码的示例:
#!/usr/bin/env python
from selenium import webdriver
from time import sleep
fp = webdriver.FirefoxProfile()
wd = webdriver.Firefox(firefox_profile=fp)
wd.get("http://someurl.html")
# appending //p here is the problem that finds only a single <a> element
elems = wd.find_element_by_xpath("/html/body/div/div/table[2]/tbody/tr/td/div/table/tbody/tr/td/div[5]/table/tbody/tr[2]//p")
print elems.get_attribute("innerHTML").encode("utf-8", 'ignore')
wd.close()
编辑:使用find_element * s * _ by_xpath而不是建议的find_element解决(感谢Alexander Petrovich,发现这一点)。
答案 0 :(得分:1)
//table[@attr='value']/tbody/tr[2]//p
find_elements_by_xpath()
方法(它返回WebElement对象列表)您将无法使用elems.get_attribute()
。相反,你必须遍历列表
elems = wd.find_elements_by_xpath("/your/xpath")
for el in elems:
print '\n' + el.get_attribute('innerHTML').encode("utf-8", 'ignore')