【问题标题】:get google links search results per search in selenium python在 selenium python 中每次搜索获取谷歌链接搜索结果
【发布时间】:2021-08-23 05:43:54
【问题描述】:

亲爱的, 我正在尝试获取谷歌搜索结果的链接,我正在使用这个 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]')

【问题讨论】:

标签: python selenium selenium-webdriver


【解决方案1】:

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

希望这会有所帮助,

# 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]

【讨论】:

  • 谢谢,效果很好,如果我会使用 xpath,你知道吗?
  • 据我所知,很难使用 xpath,因为“href”上的每个都有不同的 xpath。可以将我的答案标记为已接受吗?谢谢
  • 嘿@abbasgol,在我自己的项目中对 Xpath 进行了一些研究,想通了。可以试试这个:profiles = driver.find_elements_by_xpath("//a[contains(@href,'https://www.linkedin.com/in')]") 在这里找到了一个很好的参考:https://www.guru99.com/xpath-selenium.html#4
猜你喜欢
  • 1970-01-01
  • 2016-10-11
  • 2013-08-31
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多