【问题标题】:Fetch all links on a page within css selector 'a' for each class 'r'为每个类“r”获取css选择器“a”中页面上的所有链接
【发布时间】:2020-07-06 17:53:37
【问题描述】:

我在 python 中使用 selenium 从谷歌搜索中抓取所有相关的 URL。

我知道,如果我想在同一个类中获得一个 URL 列表,我可以执行以下操作:

div = driver.find_element_by_class_name('r')
name = div.find_elements_by_css_selector('a')

我真正想要的是 google 页面上每个类 'r' 的 href 中的 url。我试过这个:

div = driver.find_elements_by_class_name('r')
name = div.find_element_by_css_selector('a')

但我收到此错误: AttributeError: 'list' object has no attribute 'find_element_by_css_selector'

如何遍历类并提取单个 URL?

【问题讨论】:

    标签: python selenium web-scraping


    【解决方案1】:

    find_element_by_class_name 将返回elements 的列表并且列表项没有.find_element_by_css_selector 对象实现。所以你收到了这条信息。

    如果您想获取每个 div 的链接项,请更新您的代码,如下所示。

    divs = driver.find_elements_by_class_name('r')
    for div in divs:
        href= div.find_element_by_css_selector('a').get_attribute('href')
        print(href)
    

    您可以使用如下所示的xpath

    links= driver.find_elements_by_xpath("//div[@class='r']//a[h3]")
    for link in links:
        href= link.get_attribute('href')
        print(href)
    
    

    【讨论】:

      【解决方案2】:

      driver.find_elements_by_class_name 返回 Web 元素列表,而不是 WebElement 类型的单个对象。不妨试试以下方法:

      for div in driver.find_elements_by_css_selector('a .r'):
          print(div.get_attribute('href'))
      

      【讨论】:

        猜你喜欢
        • 2011-01-15
        • 1970-01-01
        • 1970-01-01
        • 2017-11-19
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        • 2013-12-18
        • 1970-01-01
        相关资源
        最近更新 更多