简体   繁体   中英

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.

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM