35

I know that I can use methods such as:

find_elements_by_tag_name() find_elements_by_id() find_elements_by_css_selector() find_elements_by_xpath() 

But what I would like to do is simply get a list of all the element IDs that exist in the page, perhaps along with the tag type they occur in.

How can I accomplish this?

1
  • 1
    Arran's answer is great, but if you want speed, then you can get the page source, and parse it for ids. This will take more coding than Arran's answer though.CommentedNov 27, 2013 at 16:36

3 Answers 3

49
from selenium import webdriver driver = webdriver.Firefox() driver.get('http://google.com') ids = driver.find_elements_by_xpath('//*[@id]') for ii in ids: #print ii.tag_name print ii.get_attribute('id') # id name as string 
0
    31

    Not had to do this before, but thinking about it logically you could use XPath to do this (may be other ways, XPath is the first thing that appears into my head).

    Use find_elements_by_xpath using the XPath //*[@id] (any element that has an ID of some sort).

    You could then iterate through the collection, and use the .tag_name property of each element to find out what kind of element it is and the get_attribute("id") method/function to get that element's ID.

    Note: This is probably going to be quite slow. After all, you are asking for a lot of information.

      7

      update for the excellent answer provided by russian_spy for new version of selenium:

      from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get('http://www.google.com/') ids = driver.find_elements(By.XPATH, '//*[@id]') # to get names use '//*[@name]' for ii in ids: print('Tag: ' + ii.tag_name) print('ID: ' + ii.get_attribute('id')) # element id as string print('Name: ' + ii.get_attribute('name')) # element name as string 
      2
      • To handle elements without names, consider str(ii.get_attribute('name')), which will print "None" instead of throwing a TypeError in your print() statement.CommentedJul 17, 2023 at 18:34
      • mysteryegg, thank you for pointing out!CommentedJul 18, 2023 at 19:22

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.