Find the ID of an element in a web page to use with Selenium

Question:

I want to automatically click on an element in a web page using the following code in Python:

driver.find_element_by_id("book appointment").click()

The web page snapshot is as follows:

Enter image description here

My problem is that I cannot find "Book Appointment" text in the page source to extract its ID. How can I find its ID?

Asked By: Hossein

||

Answers:

find_element_by_id needs an id as input. You are giving text content as input.

You may want to try some different selector. Maybe find_element_by_link_text.

There are various strategies to locate elements in a page.

Methods to locate elements in a page:

  • find_element_by_id
  • find_element_by_name
  • find_element_by_xpath
  • find_element_by_link_text
  • find_element_by_partial_link_text
  • find_element_by_tag_name
  • find_element_by_class_name
  • find_element_by_css_selector

To find multiple elements

  • find_elements_by_name
  • find_elements_by_xpath
  • find_elements_by_link_text
  • find_elements_by_partial_link_text
  • find_elements_by_tag_name
  • find_elements_by_class_name
  • find_elements_by_css_selector

For a reference on each selector, you can refer to Locating Elements.

Answered By: Hara

The HTML code provided by you doesn’t contains any Id attribute for this element, so it is not possible to locate the element by ID. Alternatively, you can locate the element with text using an XPath selector. Try the below code to locate the same:

driver.find_element_by_xpath("//a[contains(.,'Book Appointment')]")
Answered By: NarendraR