Get HTML Source of WebElement in Selenium WebDriver using Python

后端 未结 14 1760
误落风尘
误落风尘 2020-11-22 13:45

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

from selenium import webdriver
wd = webdriver.Firefox()

I know I can grab a webel

相关标签:
14条回答
  • 2020-11-22 14:08

    There is not really a straight-forward way of getting the html source code of a webelement. You will have to use JS. I am not too sure about python bindings but you can easily do like this in Java. I am sure there must be something similar to JavascriptExecutor class in Python.

     WebElement element = driver.findElement(By.id("foo"));
     String contents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element); 
    
    0 讨论(0)
  • 2020-11-22 14:08

    Sure we can get all HTML source code with this script below in Selenium Python:

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

    If you you want to save it to file:

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

    I suggest saving to a file because source code is very very long.

    0 讨论(0)
  • 2020-11-22 14:09

    And in PHPUnit selenium test it's like this:

    $text = $this->byCssSelector('.some-class-nmae')->attribute('innerHTML');
    
    0 讨论(0)
  • 2020-11-22 14:11
    WebElement element = driver.findElement(By.id("foo"));
    String contents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element); 
    

    This code really works to get JavaScript from source as well!

    0 讨论(0)
  • 2020-11-22 14:16

    Java with Selenium 2.53.0

    driver.getPageSource();
    
    0 讨论(0)
  • 2020-11-22 14:18

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

    Python:

    element.get_attribute('innerHTML')
    

    Java:

    elem.getAttribute("innerHTML");
    

    C#:

    element.GetAttribute("innerHTML");
    

    Ruby:

    element.attribute("innerHTML")
    

    JS:

    element.getAttribute('innerHTML');
    

    PHP:

    $element->getAttribute('innerHTML');
    

    Tested and works with the ChromeDriver.

    0 讨论(0)
提交回复
热议问题