-1

I would like always click on the first link on Google using selenium robot for python. So for example if I write this :

driver.get("http://www.google.com")
elem = driver.find_element_by_name("q")
elem.send_keys("Tennis")

I would like to click on the first link that appears on Google

Thank you for your help !!

2
  • It doesn't work for me sorry Commented Dec 19, 2017 at 14:00
  • 2
    Goodluck handling the day google decides your test machine is a bot and asks you to manually re-verify with captchas...half way through your testcase. Commented Dec 19, 2017 at 14:02

2 Answers 2

2

The accepted solution didn't work for me. So for anyone else that comes across that question driver.find_element_by_tag_name("cite").click() using python3 worked for me. However if you just want the link to the top search result it would be faster to use the requests and BeautifulSoup libraries as shown below

#!/usr/bin/env python3
import requests
from bs4 import BeautifulSoup
url = 'http://www.google.com/search?q=something'
page = requests.get(url)
soup = BeautifulSoup(page.text, "html.parser")
print(soup.find('cite').text)
Sign up to request clarification or add additional context in comments.

Comments

2

The xpath which is working as of Aug 2019 is

(//h3)[1]/../../a

i.e. find the first h3 tag, move to its parents and find the first a.

driver.find_element(By.XPATH, '(//h3)[1]/../../a').click()

Google will surely change something in the future and then another approach will be needed.

Old answer

The results links all (used to have) have h3 as the parent element, you can use that

driver.find_element(By.XPATH, '(//h3)[1]/a').click()

3 Comments

Thank you it's working for me !!
And do you know how can I find all the link that contain a pdf file ?
That's a separate topic. @Bilkokuya is absolutely right with his comment, the approach will break if google changes something or if they recognize you are using a Selenium script. There are different, more stable approaches. For finding PDF, inspect the PDF span in your browser and build the xpath from that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.