注意:这个问题不违反谷歌的服务条款。用例和目的符合 ToS 规定。
对象
url
是一个存储URL的原子字符向量:
url <- "https://www.google.com/search?q=Kendrick+Lamar+aoty"
我需要获取Google搜索结果返回的第一个非广告链接,并将其存储为对象
link
。这是我现在做的:
library(rvest)
url <- "https://www.google.com/search?q=Kendrick+Lamar+aoty"
search_page <- read_html(url)
first_link <- search_page %>%
html_nodes(".g:not(.g .adsbygoogle)") %>%
html_node("a") %>%
html_attr("href") %>%
URLdecode()
我收到以下错误:
Error in parse_simple_selector(stream) : Expected ')', got .
这个问题看起来像我对
html_nodes()
功能的调用。我已经通过多种方式修改了 CSS 分类器,但未能成功解决错误。根据上面的示例,我期望存储在 first_link
对象中的结果是:
https://www.albumoftheyear.org/artist/1881-kendrick-lamar/
我在
html_nodes()
函数上做错了什么(或者如果我想获得如上所示的所需输出,我缺少的其他东西)?
这个解决方案对你有好处吗?
library(rvest)
url <- "https://www.google.com/search?q=Kendrick+Lamar+aoty"
search_page <- read_html(url)
links <- search_page |>
html_elements("a") |>
html_attr("href")
i <- stringr::str_detect(links, "url\\?q\\=")
out <- stringr::str_extract(links[i], "https.*?(?=\\&)")
out