R中使用rvest爬取数据小试

总结R中使用 xpath 和 css selectors 获取标签内容(xpath功能强大,而CSS选择器通常语法比较简洁,运行速度更快些)

例:抓取下面标签的内容:

    <h3 class="lister index unbold text"><span>小明他很忙</span></h3>

(1)使用xpath(与python里使用xpath 相似,R中可以使用html_text() 获取标签中的内容,如"<span>小明他很忙</span>"中标签内容为“小明他很忙”; 使用html_att("属性") 获取属性值):

    rvest::html_nodes(webPage, xpath = '//h3[@class="lister index unbold text"]/span') %>% rvest::html_text()

(2)使用css选择器

    使用之前,我们首先要了解一下几点内容:

    1.在css中 "class" 用 "." 映射; "id" 用 "#" 映射

    2.在css选择器中,如果class里带的空格,用.来代替空格

    h3 class="lister index unbold text" -> h3.lister index unbold text(class里有空格) -> h3.lister.index.unbold.text

    rvest::html_nodes(webPage, css = "h3.lister.index.unbold.text span") %>% rvest::html_text()
1.安装rvest、xml2包
    library(pacman)
    pacman::p_load(rvest, xml2)
2.载入rvest、xml2包
    # 载入工具包
    library(rvest)
    library(xml2)
3.使用两个工具包爬去数据
    # 设置爬取的网址     
    url <- "https://www.imdb.com/search/title?count=100&release_date=2016,2016&title_type=feature"
    # 获取页面内容(页面源码)
    webPage <- xml2::read_html(x = url, encoding = "UTF-8") 

    # ======= 方法1 使用xpath ==========
    # 电影名称
    movieName <- rvest::html_nodes(webPage, xpath = '//h3[@class="lister-item-header"]/a/text()')

    # === 备注 ===
    # 如果用到属性里的值,使用函数rvest::html_att(),如rvest::html_att("alt")
    # rvest::html_nodes(webPage, xpath = '//div[@class="lister-item-image float-left"]/a/img') %>% rvest::html_attr("alt")
    
    # 上映年份
    year <- rvest::html_nodes(webPage, xpath = '//span[@class="lister-item-year text-muted unbold"]/text()')

    # ======= 方法2 使用css选择择器 =====
    # 电影排序
    movieRank <- rvest::html_nodes(webPage, css = "span.lister-item-year.text-muted.unbold") %>% rvest::html_text()

猜你喜欢

转载自www.cnblogs.com/xiaomingzaixian/p/9919074.html