我使用Python绑定来运行Selenium WebDriver:

from selenium import webdriver
wd = webdriver.Firefox()

我知道我可以像这样抓取一个webelement:

elem = wd.find_element_by_css_selector('#my-id')

我知道我可以得到整页的源代码…

wd.page_source

但是是否有一种获取“元素源”的方法?

elem.source   # <-- returns the HTML as a string

Python的Selenium WebDriver文档基本上不存在,我在代码中没有看到任何支持该功能的东西。

访问一个元素(及其子元素)的HTML的最佳方法是什么?


当前回答

获得我喜欢的渲染HTML的方法如下:

driver.get("http://www.google.com")
body_html = driver.find_element_by_xpath("/html/body")
print body_html.text

但是,上面的方法删除了所有的标记(是的,嵌套标记也是如此),只返回文本内容。如果您对获取HTML标记也感兴趣,那么可以使用下面的方法。

print body_html.getAttribute("innerHTML")

其他回答

如果你对Python中Selenium Remote Control的解决方案感兴趣,下面是如何获取innerHTML:

innerHTML = sel.get_eval("window.document.getElementById('prodid').innerHTML")

在PHPUnit Selenium测试中,它是这样的:

$text = $this->byCssSelector('.some-class-nmae')->attribute('innerHTML');

在PHP Selenium WebDriver中,你可以像这样获得页面源代码:

$html = $driver->getPageSource();

或者像这样获取元素的HTML:

// innerHTML if you need HTML of the element content
$html = $element->getDomProperty('outerHTML');

当然,我们可以用下面的脚本在Selenium Python中获得所有的HTML源代码:

elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")

如果你想保存到文件:

with open('c:/html_source_code.html', 'w') as f:
f.write(source_code.encode('utf-8'))

我建议保存到一个文件,因为源代码非常非常长。

实际上没有一种直接的方法来获取web元素的HTML源代码。你必须使用JavaScript。我不太确定python绑定,但在Java中可以很容易地这样做。我相信在Python中一定有类似JavascriptExecutor类的东西。

 WebElement element = driver.findElement(By.id("foo"));
 String contents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element);