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

其他回答

在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")

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

$element->getDomProperty('innerHTML');

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

您可以读取innerHTML属性以获取元素内容的源,也可以读取outerHTML以获取带有当前元素的源。

Python:

element.get_attribute('innerHTML')

Java:

elem.getAttribute("innerHTML");

C#:

element.GetAttribute("innerHTML");

Ruby:

element.attribute("innerHTML")

JavaScript:

element.getAttribute('innerHTML');

PHP:

$element->getAttribute('innerHTML');

它在ChromeDriver上进行了测试和使用。

我希望这能有所帮助: http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html

下面介绍Java方法:

java.lang.String    getText() 

但不幸的是,它在Python中不可用。因此,您可以将方法名称从Java转换为Python,并尝试使用现有方法的另一种逻辑,而无需获得整个页面的源代码……

E.g.

 my_id = elem[0].get_attribute('my-id')