在硒python中每次搜索获取谷歌链接搜索结果

时间:2021-06-05 12:31:06

标签: python selenium selenium-webdriver

亲爱的, 我正在尝试获取谷歌搜索结果的链接,我正在使用这个 profiles = driver.find_elements_by_xpath('//*[@class="r"]/a[1]') 这工作正常,我现在正在使用它,但没有给我结果

            import csv
            from parsel import Selector
            from selenium import webdriver
            from selenium.webdriver.common.keys import Keys
            import time
            import itertools
            import random
            listlong = []
            
            driver = webdriver.Chrome('C:/chromedriver.exe')
            driver.get('https://www.google.com/search?q=&num=200&start=0&sourceid=chrome')
            time.sleep(random.randint(10,11))
            search_input = driver.find_element_by_name('q')
            search_input.send_keys('site:linkedin.com/in/ AND USA')
            time.sleep(3)
            search_input.send_keys(Keys.RETURN)
            time.sleep(3)
            # grab all linkedin profiles from first page at Google
            profiles = driver.find_elements_by_xpath('//*[@class="r"]/a[1]')
            time.sleep(8)
            profiles = [profile.get_attribute('href') for profile in profiles]
            listprof = profiles.copy()
            listlong.extend(listprof)
            print(profiles)
            print("f1")
            print(listprof)
            print("f2")
            print(listlong)
            print("f3")
            driver.quit()

什么是xpath可以代替这个 driver.find_elements_by_xpath('//*[@class="r"]/a[1]')

1 个答案:

答案 0 :(得分:2)

基于MBAas的回答,我试过了。我添加了它,以便首先找到搜索结果,然后根据 css 选择器(“div > div > div.yuRUbf > a”)进行查找。

希望这会有所帮助,enter image description here

# grab all linkedin profiles from first page at Google
search_result = driver.find_elements_by_css_selector('div.g')
profiles = driver.find_elements_by_css_selector("div > div > div.yuRUbf > a")
time.sleep(8)
profiles = [profile.get_attribute('href') for profile in profiles]