【问题标题】:How to click on the second link in google search result list using selenium web driver如何使用 selenium 网络驱动程序点击谷歌搜索结果列表中的第二个链接
【发布时间】:2020-06-08 20:51:36
【问题描述】:

我想使用 selenium-web-driver 在谷歌搜索区域中点击第二个链接

(需要一种适合任何 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)

【问题讨论】:

    标签: python google-chrome selenium-webdriver automation


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-05
      • 2022-01-18
      • 1970-01-01
      • 2018-10-03
      • 2019-03-13
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多