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


当前回答

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

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)。

其他回答

获得我喜欢的渲染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")

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

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

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

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