Obtener código HTML de WebElement en Selenium WebDriver usando Python


Estoy usando los enlaces de Python para ejecutar Selenium WebDriver.

from selenium import webdriver
wd = webdriver.Firefox()

Sé que puedo agarrar un webelement así...

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

Y sé que puedo obtener la fuente de página completa con...

wd.page_source

¿Pero hay de todos modos para obtener la "fuente del elemento"?

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

Los documentos de selenium webdriver para Python son básicamente inexistentes y no veo nada en el código que parezca habilitar esa funcionalidad.

Cualquier pensamiento sobre la mejor manera de acceder al HTML de un elemento (y sus hijos)?

Author: Mohsin Awan, 2011-09-01

13 answers

Puede leer el atributo innerHTML para obtener la fuente del contenido del elemento o outerHTML para la fuente con el elemento actual.

Python:

element.get_attribute('innerHTML')

Java:

elem.getAttribute("innerHTML");

C#:

element.GetAttribute("innerHTML");

Ruby:

element.attribute("innerHTML")

JS:

element.getAttribute('innerHTML');

PHP:

$elem.getAttribute('innerHTML');

Probado y funciona con el ChromeDriver.

 539
Author: Nerijus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-16 15:56:37

Realmente no hay una forma sencilla de obtener el código fuente html de un webelement. Tendrás que usar JS. No estoy muy seguro de los enlaces de Python, pero puedes hacer esto fácilmente en Java. Estoy seguro de que debe haber algo similar a la clase JavascriptExecutor en Python.

 WebElement element = driver.findElement(By.id("foo"));
 String contents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element); 
 78
Author: nilesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-24 19:10:49

Seguro que podemos obtener todo el código fuente HTML con este script a continuación en Python Selenium:

elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")

Si quieres guardarlo en archivo:

f = open('c:/html_source_code.html', 'w')
f.write(source_code.encode('utf-8'))
f.close()

Sugiero guardar en un archivo porque el código fuente es muy, muy largo.

 56
Author: Mark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-11 18:40:30

En Ruby, usando selenium-webdriver (2.32.1), hay un método page_source que contiene toda la fuente de página.

 10
Author: John Alberts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-24 19:11:35

Usar el método de atributo es, de hecho, más fácil y más sencillo.

Usando Ruby con las gemas Selenium y PageObject, para obtener la clase asociada con un determinado elemento, la línea sería element.attribute(Class).

El mismo concepto se aplica si desea obtener otros atributos vinculados al elemento. Por ejemplo, si quisiera la cadena de un elemento, element.attribute(String).

 3
Author: Tiffany G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-22 16:07:00

Parece anticuado, pero que esté aquí de todos modos. La forma correcta de hacerlo en su caso:

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

O

html = elem.get_attribute('innerHTML')

Ambos funcionan para mí (selenium-server-standalone-2.35.0)

 3
Author: nefski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-13 21:45:33

Java con Selenio 2.53.0

driver.getPageSource();
 1
Author: WltrRpo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-29 21:25:03

Espero que esto pueda ayudar: http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html

Aquí se describe el método Java:

java.lang.String    getText() 

Pero desafortunadamente no está disponible en Python. Por lo tanto, puede traducir los nombres de los métodos a Python desde Java y probar otra lógica utilizando métodos actuales sin obtener toda la fuente de página...

Por ejemplo

 my_id = elem[0].get_attribute('my-id')
 1
Author: oleksii.burdin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-07 23:09:29

Y en la prueba de selenio PHPUnit es así:

$text = $this->byCssSelector('.some-class-nmae')->attribute('innerHTML');
 0
Author: Zorgijs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-30 10:42:42

Si está interesado en una solución para Control remoto en Python, aquí está cómo obtener innerHTML:

innerHTML = sel.get_eval("window.document.getElementById('prodid').innerHTML")
 0
Author: StanleyD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-07 22:35:04

InnerHTML devolverá elemento dentro del elemento seleccionado y outerHTML devolverá dentro de HTML junto con el elemento que ha seleccionado

Ejemplo :- Ahora supongamos que su elemento es el siguiente

<tr id="myRow"><td>A</td><td>B</td></tr>

Salida del elemento innerHTML

<td>A</td><td>B</td>

Salida de elemento outerHTML

<tr id="myRow"><td>A</td><td>B</td></tr>

Ejemplo en vivo: -

Http://www.java2s.com/Tutorials/JavascriptDemo/f/find_out_the_difference_between_innerhtml_and_outerhtml_in_javascript_example.htm

Infra usted encontrará la sintaxis que requieren según el enlace diferente. Cambie el innerHTML a outerHTML según sea necesario.

Python:

element.get_attribute('innerHTML')

Java:

elem.getAttribute("innerHTML");

Si desea que toda la página HTML utilice el siguiente código: -

driver.getPageSource();
 0
Author: Shubham Jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-03 07:18:46

El método para obtener el HTML renderizado que prefiero es el siguiente:

driver.get("http://www.google.com")
body_html = driver.find_element_by_xpath("/html/body")
print body_html.text

Sin embargo, el método anterior elimina todas las etiquetas( sí, las etiquetas anidadas también ) y devuelve solo contenido de texto. Si está interesado en obtener el marcado HTML también, use el método a continuación.

print body_html.getAttribute("innerHTML")
 0
Author: Rusty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-05 04:57:48
WebElement element = driver.findElement(By.id("foo"));
String contents = (String)((JavascriptExecutor)driver).executeScript("return      arguments[0].innerHTML;", element); 

¡Este código realmente funciona para obtener JavaScript del código fuente también!

 -1
Author: Ilya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-05 14:25:50