我使用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的最佳方法是什么?


当前回答

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

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

其他回答

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

这段代码真的可以从源代码获得JavaScript !

这对我来说非常有效。

element.get_attribute('innerHTML')

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

$html = $driver->getPageSource();

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

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

Java与Selenium 2.53.0

driver.getPageSource();

使用execute_script get html

bs4(BeautifulSoup)也可以快速访问html标签。

from bs4 import BeautifulSoup
html = adriver.execute_script("return document.documentElement.outerHTML")
bs4_onepage_object=BeautifulSoup(html,"html.parser")
bs4_div_object=bs4_onepage_object.find_all("atag",class_="attribute")