4

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 link that come in the organic result will be chennai.craiglist.org. But I am quiet not sure about how to do this.

from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import Select
    from selenium.common.exceptions import NoSuchElementException
    import unittest, time, re

    class Browse(unittest.TestCase):
    def setUp(self):
    self.driver = webdriver.Firefox()
    self.driver.implicitly_wait(30)
    self.base_url = "http://google.com/"

    filename = 'test.csv'
    line_number = 1
    with open(filename, 'rb') as f:
        mycsv = csv.reader(f)
        mycsv = list(mycsv)
        self.cityname=mycsv[line_number][0]
        self.username=mycsv[line_number][1]
        self.password=mycsv[line_number][2]
        self.verificationErrors = []

def test_browse(self):
    driver = self.driver
    driver.get(self.base_url + "/")
    driver.find_element_by_id("gbqfq").send_keys(self.cityname)

I wanna know what should come after this line?

UPDATE

right now I am giving like

driver.find_elements_by_xpath(".//*[@id='rso']//div//h3/a")[:1].click()

I am not sure if it will work or not.

4

4 回答 4

5

xpath您选择的是“好的”,但可能不是最好的。

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
于 2013-10-07T13:31:45.593 回答
3

这适用于谷歌搜索结果。

results = driver.find_elements_by_xpath('//div[@class="r"]/a/h3')  # finds webresults
results[0].click(). # clicks the first one
于 2019-02-17T19:16:51.617 回答
1

我一直在使用driver.find_element_by_tag_name("cite").click()对我有用的python3。但是,如果您只想要顶部搜索结果的链接,那么使用请求和 BeautifulSoup 库会更快,如下所示

#!/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)
于 2019-05-17T16:25:25.283 回答
1
  1. “iUh30”是第一个谷歌搜索结果的类名,与搜索的关键字无关。
  2. .text 将获取 locator(class_name) 指向的 url
  3. driver.get() 将导航到 url

driver.get(driver.find_element_by_class_name("iUh30").text)

于 2021-10-09T19:21:58.463 回答