如何使用硒Web驱动程序单击Google搜索结果列表中的第二个链接

时间:2020-02-25 07:11:53

标签: python google-chrome selenium-webdriver automation

我想使用selenium-web-driver在Google搜索区域中点击结果中的第二个链接

(需要一种适合任何Google搜索结果的方法)

example page

这是我的代码,如何修改if语句

import speech_recognition as sr
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("detach", True)

global driver
driver = webdriver.Chrome('C:\Windows\chromedriver.exe', options=chrome_options)
chrome_options.add_argument("--start-maximized")
wait = WebDriverWait(driver, 10)

def google(text): 
    if "first link" in text: 
       RESULTS_LOCATOR = "//div/h3/a"

        WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.XPATH, RESULTS_LOCATOR)))

        page1_results = driver.find_elements(By.XPATH, RESULTS_LOCATOR)

        for item in page1_results:
            print(item.text)
        # driver.find_element_by_class_name().click()
    else:
        ggwp=text.replace(" ", "")
        driver.get("https://www.google.com")
        driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input').send_keys(ggwp)
        driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[3]/center/input[1]').send_keys(Keys.ENTER)

1 个答案:

答案 0 :(得分:1)

第二个链接可以放在不同的div-s中。

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

browser = webdriver.Chrome(executable_path=os.path.abspath(os.getcwd()) + "/chromedriver")
link = 'http://www.google.com'
browser.get(link)

# search keys
search = browser.find_element_by_name('q')
search.send_keys("python")
search.send_keys(Keys.RETURN)

# click second link
for i in range(10):
    try:
        browser.find_element_by_xpath('//*[@id="rso"]/div['+str(i)+']/div/div[2]/div/div/div[1]/a').click()
        break
    except:
        pass