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


当前回答

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

$html = $driver->getPageSource();

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

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

其他回答

在Ruby中,使用selenium-webdriver(2.32.1),有一个包含整个页面源代码的page_source方法。

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

实际上,使用属性方法更简单、更直接。

将Ruby与Selenium和PageObject宝石一起使用,以获得与某个元素相关联的类,行代码为element.attribute(class)。

如果您希望获得与元素绑定的其他属性,同样的概念也适用。例如,如果我想要一个元素的字符串,element.attribute(string)。

Java与Selenium 2.53.0

driver.getPageSource();

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

$html = $driver->getPageSource();

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

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