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


当前回答

使用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")

其他回答

当然,我们可以用下面的脚本在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'))

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

它看起来过时了,但不管怎样,就让它留在这里吧。在你的情况下,正确的做法是:

elem = wd.find_element_by_css_selector('#my-id')
html = wd.execute_script("return arguments[0].innerHTML;", elem)

or

html = elem.get_attribute('innerHTML')

两者都适合我(selenium-server-standalone-2.35.0)。

在当前版本的php-webdriver(1.12.0+)中,您必须使用

$element->getDomProperty('innerHTML');

正如本期文章所指出的:https://github.com/php-webdriver/php-webdriver/issues/929

实际上没有一种直接的方法来获取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);

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

$html = $driver->getPageSource();

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

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