问题:无法使用来自 r 的 rvest 包读取带有 read_html 的网页

我正在尝试从亚马逊获取产品评论者的位置。例如,这个网页

[https://www.amazon.com/gp/profile/amzn1.account.AH55KF4JK5IKKJ77MPOLHOR4YAQQ/refu003dcm_cr_dp_d_gw_tr?ieu003dUTF8][1]

我需要得到HAINESVILLE, ILLINOIS, United States

我使用 rvest 包进行网页抓取。

这是我所做的:

library(rvest)       
url='https://www.amazon.com/gp/profile/amzn1.account.AH55KF4JK5IKKJ77MPOLHOR4YAQQ/ref=cm_cr_dp_d_gw_tr?ie=UTF8'
page = read_html(url)

我收到如下错误:

Error in open.connection(x, "rb") : HTTP error 403.

但是,以下工作:

con <- url(url, "rb")
page = read_html(con)

但是,对于我阅读的页面,我无法提取任何文本。例如,我想提取审稿人的位置。

page %>%
    html_nodes("#customer-profile-name-header .a-size-base a-color-base")%>%
    html_text()

我什么都没有

character(0)

谁能帮忙弄清楚我做错了什么?提前非常感谢。

解答

这应该有效:

library(dplyr)
library(rvest)
library(stringr)

# get url
url='https://www.amazon.com/gp/profile/amzn1.account.AH55KF4JK5IKKJ77MPOLHOR4YAQQ/ref=cm_cr_dp_d_gw_tr?ie=UTF8'

# open page
con <- url(url, "rb")
page = read_html(con)

# get the desired information, using View Page Source
page %>%
  html_nodes(xpath=".//script[contains(., 'occupation')]")%>%
  html_text() %>% as.character() %>% str_match(.,"location\":\"(.*?)\",\"personalDescription") -> res

res[,2]
Logo

ModelScope旨在打造下一代开源的模型即服务共享平台,为泛AI开发者提供灵活、易用、低成本的一站式模型服务产品,让模型应用更简单!

更多推荐