Search code examples
pythonselenium-webdriverxpathmeta-tags

How get the value of a 'charset' meta element with Xpath?


With Selenium webdriver, I'm trying to parse a charset meta element from a page.

<meta charset="UTF-8">

This is what I have so far

from selenium.webdriver.common.by import By

xpath='//meta[@charset]'
charset_meta_element = driver.find_element(By.XPATH, xpath)

I get a WebElement object. How from this element I can get the value (eg: 'UTF-8')?


Solution

  • You can use the get_attribute() method like so.

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    driver = webdriver.Chrome()
    driver.get("file:///index.html")  # Replace with the actual path
    
    xpath = '//meta[@charset]'
    charset_meta_element = driver.find_element(By.XPATH, xpath)
    
    # Get the value of the charset attribute
    charset_value = charset_meta_element.get_attribute("charset")
    print("Charset:", charset_value)
    
    driver.quit()