Selenium: WebDriver "get" function returns a string

Question:

I’m trying to develop a browser automation with selenium. I need to download HTML sources and analyze them. I’m writing my code like this:

browser = webdriver.Chrome()
browser.get(url)
htmlDoc300 = browser.page_source
error_text = htmlDoc300.find_element(By.ID, 'ctl00_MainContentPlaceHolder_ModalErrorText').text

The last line returns the error "’str’ object has no attribute ‘find_element", so "page_source" returns a string and not a driver. How can i fix it? Is it possible to cast the str in a webDrvier?

Asked By: Matteo Caruso

||

Answers:

My friend, browser.page_source returns the HTML content which is of an str datatype.

print(type(browser.page_source))
>> <class 'str'>

and as you get the error, str doesn’t have "find_element" attribute.

print(type(browser))
>> <class 'selenium.webdriver.chrome.webdriver.WebDriver'>

I hope you noticed the difference. So you need to find your desired element on the browser itself like this :

error_text = browser.find_element(By.ID, 'ctl00_MainContentPlaceHolder_ModalErrorText').text
Answered By: Ajeet Verma
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.