• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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\']")

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
R语言爬虫:CSS方法与XPath方法对比(表格介绍)发布时间:2022-07-18
下一篇:
豆瓣电影R语言爬虫和数据分析.发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap