How to click on the first result on google using selenium python

前端 未结 3 1484
情书的邮戳
情书的邮戳 2021-01-03 06:23

I am trying to click on the first result on the google result. Here is my code where I am entering chennai craiglist which is read from csv file. So I am sure the first lin

相关标签:
3条回答
  • 2021-01-03 06:27

    The xpath you have chosen is 'ok' but probably not the best.

    result = driver.find_elements_by_xpath("//ol[@id="rso"]/li")[0] //make a list of results and get the first one
    result.find_element_by_xpath("./div/h3/a").click() //click its href
    
    0 讨论(0)
  • 2021-01-03 06:47

    I've been using driver.find_element_by_tag_name("cite").click() in python3 which has 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)
    
    0 讨论(0)
  • 2021-01-03 06:49

    This works great with google results.

    results = driver.find_elements_by_xpath('//div[@class="r"]/a/h3')  # finds webresults
    results[0].click(). # clicks the first one
    
    0 讨论(0)
提交回复
热议问题