【问题标题】:Scraping the content of all div tags with a specific class使用特定类抓取所有 div 标签的内容
【发布时间】:2018-06-30 14:03:32
【问题描述】:

我正在从网站上抓取特定类 div 中出现的所有文本。在下面的示例中,我想提取“a”类 div 中的所有内容。

site <- "<div class='a'>Hello, world</div>
  <div class='b'>Good morning, world</div>
  <div class='a'>Good afternoon, world</div>"

我想要的输出是...

"Hello, world"
"Good afternoon, world"

下面的代码从每个 div 中提取文本,但我不知道如何只包含 class="a"。

library(tidyverse)
library(rvest)

site %>% 
  read_html() %>% 
  html_nodes("div") %>% 
  html_text()

# [1] "Hello, world"          "Good morning, world"   "Good afternoon, world"

使用 Python 的 BeautifulSoup,它看起来像 site.find_all("div", class_="a")

【问题讨论】:

    标签: r rvest


    【解决方案1】:

    div with class = "a" 的 CSS 选择器是 div.a

    site %>% 
      read_html() %>% 
      html_nodes("div.a") %>% 
      html_text()
    

    或者你可以使用 XPath:

    html_nodes(xpath = "//div[@class='a']")
    

    【讨论】:

      【解决方案2】:
      site %>% 
        read_html() %>% 
        html_nodes(xpath = '//*[@class="a"]') %>% 
        html_text()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-27
        • 1970-01-01
        • 2012-09-14
        • 2012-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-21
        相关资源
        最近更新 更多