Home > Software engineering >  How to search in a webpage using selenium despite using correct search id
How to search in a webpage using selenium despite using correct search id

Time:01-16

I am trying to search a web page using selenium. Below is the HTML code snippet of search page.

<div >
     <input id="searchString" type="text"  placeholder="Search" aria-label="Search" required="" autocomplete="off">
     <input type="hidden" id="searchTargetUrl" value="/en/search">
     <a  href="#">
     <span ></span>
     </a>
</div>

The above one is taken from https://www.gartner.com.

I am using below python code to use the search page.

url = 'https://www.gartner.com/'
driver = webdriver.Chrome(executable_path='path to chrome web driver')
driver.get(url)
elem = driver.find_element_by_id("SearchString")
elem.send_keys("Risk Management Solution")
elem.send_keys(keys.RETURN)

Strange thing is I am getting the below error:

NoSuchElementException: no such element: Unable to locate element: {"method":"css 
selector","selector":"[id="SearchString"]"}
(Session info: chrome=97.0.4692.71)

I have tried below as well:

elem = driver.find_element_by_xpath("""//input[@id="searchTargetUrl"]/input[@value = "Risk Management Solution""")

Getting similar error:

InvalidSelectorException: invalid selector: Unable to locate an element with the xpath 
expression //input[@id="searchTargetUrl"]/input[@value = "Risk Management Solution because 
of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string 
'//input[@id="searchTargetUrl"]/input[@value = "Risk Management Solution' is not a valid 
XPath expression.
(Session info: chrome=97.0.4692.71)

I am novice to selenium and therefore asking for any clue.

Update

I have copied the full xpath of the search page from the above site.

//*[@id="gartnerinternalpage-9ac4556e05"]/div[2]/div/div/div/div/div/div/section/div/div/div[1]/div[2]/div/div[1]/input

So I had replaced the above xpath string in the python code and added //input[@value={0}]

Still no luck!!

CodePudding user response:

The search field with id searchString is hidden, by default. It is present in the DOM but not visible.

To be able to enter anything in that field, you first need to click on the following button which can be located by cssSelector - a.dropdown-toggle span.gcom-icon-search:

enter image description here

You can write this line of code after navigating to the url:

driver.find_element_by_css_selector('a.dropdown-toggle span.gcom-icon-search').click()

After clicking on the above object, you will be able to see the search field where you want to enter the text: enter image description here

CodePudding user response:

The Search field is not visible by default, to send a character sequence to the search field you need to gartner_com

  •  Tags:  
  • Related