使用 Python 在 Selenium WebDriver 中获取 WebElement 的 HTML 源代码 [英] Get HTML source of WebElement in Selenium WebDriver using Python

查看:79
本文介绍了使用 Python 在 Selenium WebDriver 中获取 WebElement 的 HTML 源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 绑定来运行 Selenium WebDriver:

I'm using the Python bindings to run Selenium WebDriver:

from selenium import webdriver
wd = webdriver.Firefox()

我知道我可以像这样抓取网页元素:

I know I can grab a webelement like so:

elem = wd.find_element_by_css_selector('#my-id')

而且我知道我可以通过...获得完整的页面源代码

And I know I can get the full page source with...

wd.page_source

但是有没有办法获得元素源"?

But is there a way to get the "element source"?

elem.source   # <-- returns the HTML as a string

Python 的 Selenium WebDriver 文档基本上不存在,我在代码中看不到任何似乎启用该功能的内容.

The Selenium WebDriver documentation for Python are basically non-existent and I don't see anything in the code that seems to enable that functionality.

访问元素(及其子元素)的 HTML 的最佳方式是什么?

What is the best way to access the HTML of an element (and its children)?

推荐答案

您可以通过读取 innerHTML 属性来获取元素的 content 的来源>outerHTML 用于当前元素的源代码.

You can read the innerHTML attribute to get the source of the content of the element or outerHTML for the source with the current element.

蟒蛇:

element.get_attribute('innerHTML')

Java:

elem.getAttribute("innerHTML");

C#:

element.GetAttribute("innerHTML");

红宝石:

element.attribute("innerHTML")

JavaScript:

JavaScript:

element.getAttribute('innerHTML');

PHP:

$element->getAttribute('innerHTML');

它已经过测试并与 ChromeDriver 一起使用.

It was tested and worked with the ChromeDriver.

这篇关于使用 Python 在 Selenium WebDriver 中获取 WebElement 的 HTML 源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆