user12301187
user12301187

Reputation:

How to click on the first google search result with python selenium?

I am trying to write program that will click on the first google search link that appears. My code is:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys 
import time

driver = webdriver.Firefox()
driver.get("https://www.google.com/")
search = driver.find_element_by_name("q")
search.clear()
search.send_keys("bee movie script")
search.send_keys(Keys.RETURN)
time.sleep(3)
assert "No results found." not in driver.page_source
result = driver.find_element_by_xpath('/html/body/div[6]/div[3]/div[8]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div[1]/a/h3')
result.click()

I've tried a variation of things for result, but the automation is unable to find the element. I copied the xpath from inspect element, but I get an error that:

NoSuchElementException: Message: Unable to locate element: /html/body/div[6]/div[3]/div[8]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div[1]/a/h3

Am I doing this html incorrectly and how can I fix it? Thank you.

Upvotes: 2

Views: 4953

Answers (2)

supputuri
supputuri

Reputation: 14135

You can use the below xpath and css to select the nth link.

xpath: Using the index

driver.find_element_by_xpath('(//div[@class="r"]/a)[1]').click()

If you want to access the first matching element you can simply use .find_element_xpath and script will pick the first element though there are multiple elements matching with the given locator strategy be it xpath, css or anything.

driver.find_element_by_css_selector("div.r a h3").click()

Upvotes: 0

user12301187
user12301187

Reputation:

I found a solution with:

results = driver.find_elements_by_xpath('//div[@class="r"]/a/h3')  # finds webresults
results[0].click(). # clicks the first one

Upvotes: 4

Related Questions