html - 使用 R XML 包进行 Web 抓取 - xpathSapply
问题描述
我正在尝试从该网站提取所有购物中心名称(例如 CityPlaza、Fashion Walk): https ://www.discoverhongkong.com/eng/explore/shopping/major-shopping-malls-throughout-city.html
查看 html 代码,看起来购物中心的文本都存储在标签“h5”下。因此,我使用以下代码尝试提取,但它没有给我想要的文本。
url <- "https://www.discoverhongkong.com/eng/explore/shopping/major-shopping-malls-throughout-city.html"
txt = getURL(url)
PARSED <- htmlParse(txt)
mall_text <- xpathSApply(PARSED, "//h5", xmlValue)
这肯定与我在 xpathSApply 函数中作为参数放置的路径有关,因为我对 html 知之甚少。有人可以帮忙吗?
解决方案
商城推荐是动态加载的,遗憾的是无法通过这种方式获取。
如果您在浏览器中右键单击网页,转到“检查元素”,单击“网络”选项卡并刷新页面,您可以看到正在发出的一堆 JSON/XHR 请求:
其中一个网址是this。您可以看到它包含您想要的 JSON 格式的信息。
这可以很容易地使用例如jsonlite
包加载到 R 中。
library(jsonlite)
url <- "https://www.discoverhongkong.com/eng/explore/shopping/major-shopping-malls-throughout-city/_jcr_content/root/responsivegrid/dhkContainer/container/recommendationtiles_.recommendation-tiles.recommendationtiles_.json?path=/content/dhk/intl/en/explore/shopping/major-shopping-malls-throughout-city"
result <- read_json(url)
sapply(result$data, function(x) x$title)
这使
[1] "Cityplaza" "Fashion Walk"
[3] "Horizon Plaza" "Hysan Place"
[5] "ifc mall" "Island Beverley"
[7] "LANDMARK" "Lee Garden One - Six"
[9] "Lee Theatre and Leighton" "Lee Tung Avenue"
[11] "Pacific Place" "Peak Galleria"
[13] "SOGO Causeway Bay Store" "Times Square"
[15] "Western Market" "WTC"
推荐阅读
- flask - 无法使用 setextremes 显示 highcharts 图表
- oracle - 遇到符号PLSQL
- javascript - 编写 ajax 查询的更紧凑的方式
- html - 客户 X 或客户 Y 必须像像素一样读取其编号。我没有在没有给出语法错误的情况下添加它
- javascript - 如何选择一个
- 使用 JS 标记
- python - 为什么硒模块不能为我正常工作
- node.js - 如何从 localhosting 更改为域名?
- node.js - 处理从 React js 上传多张图片
- ios - 是否可以“切片”附加到 iOS 应用程序资产的视频?
- reactjs - Suspense component gets called before the data actually loads