XPath - 选择所有<p>元素不起作用</p>

时间:2013-09-20 07:23:13

标签: python xpath selenium

我有一些基本的selenium代码和一个表现良好的xpath表达式。

xpath:

/html/body/div/div/table[2]/tbody/tr/td/div/table/tbody/tr//td/div[5]/table/tbody/tr[2]

选择我感兴趣的部分,其中包含许多

元素。

然而,追加&#39; // p&#39;像这样:

/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,发现这一点)。

1 个答案:

答案 0 :(得分:1)

  1. 请勿使用此类定位器。稍微缩短一点。像//table[@attr='value']/tbody/tr[2]//p
  2. 之类的东西
  3. 要选择多个元素,请使用find_elements_by_xpath()方法(它返回WebElement对象列表)
  4. 您将无法使用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')