Selenium webdriver: How do I find ALL of an element's attributes?

后端 未结 4 1087
[愿得一人]
[愿得一人] 2020-11-30 23:44

In the Python Selenium module, once I have a WebElement object I can get the value of any of its attributes with get_attribute():

f         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-01 00:15

    Here is my attempt at an answer. I do only tested it on the search box of google's homepage. I made use of @alecxe's answer above about 'outerHTML' Having obtained the html, I used a regular expression ([a-z]+-?[a-z]+_?)='?"? to match the attribute names. I think the regex would just have to be modified to match an increasing number of cases. But the essential name we need is "whatever is behind the equal sign."

    Given a webElement

    def get_web_element_attribute_names(web_element):
        """Get all attribute names of a web element"""
        # get element html
        html = web_element.get_attribute("outerHTML")
        # find all with regex
        pattern = """([a-z]+-?[a-z]+_?)='?"?"""
        return re.findall(pattern, html)
    

    Test it on the below code

    import re
    from selenium import webdriver
    
    driver = webdriver.Firefox()
    google = driver.get("http://www.google.com")
    
    driver.find_element_by_link_text("English").click()
    search_element = driver.find_element_by_name("q")
    get_web_element_attribute_names(search_element)
    

    output:

    ['class', 'id', 'maxlength', 'name', 'autocomplete', 'title', 'value', 'aria-label', 'aria-haspopup', 'role', 'aria-autocomplete', 'style', 'dir', 'spellcheck', 'type']
    

提交回复
热议问题