R语言爬虫:CSS方法与XPath方法对比(代码实现)

CSS选择器和XPath方法都是用来定位DOM树的标签,只不过两者的定位表示形式上存在一些差别:

  • CSS 方法提取节点
library("rvest")
single_table_page <- read_html("single-table.html")
# 提取url里的所有表格
html_table(single_table_page)
html_table(html_node(single_table_page,"table"))
products_page <- read_html("./case/products.html")
products_page %>% html_nodes(".product-list li .name") %>% html_text() 
product_items <- products_page %>% html_nodes(".product-list li")
data.frame(name = product_items %>% html_nodes(".name") %>% html_text(), 
           price = product_items %>% html_nodes(".price") %>%html_text() 
           %>% str_replace_all(pattern="\\$",replacement="") %>% 
               as.numeric(), stringsAsFactors = FALSE)
  • XPath 方法提取节点
page <- read_html("./case/new-products.html")
#查找所有p节点
page %>% html_nodes(xpath="//p")
#CSS's way
page %>% html_nodes("p")
# 找到所有具有class属性的li标签
# xpath's way
page %>% html_nodes(xpath="//li[@class]")
# CSS's way
page %>% html_nodes("li[class]")
# 找到id=‘list’的div标签下的所有li标签
# xparth's way
page %>% html_nodes(xpath="//div[@id='list']/ul/li")
# CSS's way
page %>% html_nodes("div#list > ul > li")
# 查找包含p节点的所有div节点
page %>% html_nodes(xpath="//div[p]")
# 查找所有class值为“info-value”,文本内容为“Good”的span节点
page %>% html_nodes(xpath = "//span[@class='info-value' and text()='Good']")

转载于:https://www.cnblogs.com/xihehe/p/8310089.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值