【发布时间】:2020-12-02 13:31:27
【问题描述】:
data_before <- read_excel("C:/Users/babyb/Desktop/Derrick Rancourt/Canadian Biotech Companies.xlsx", col_names = FALSE)
companyName <- subset(na.omit(data_before, cols = 1), select = -c(2, 3, 4))
data_now <- setNames(data.table(matrix(nrow=0, ncol=2)), c("Company Name", "Website"))
for(value in companyName){
searchTerm <- paste(value)
print(searchTerm)
firstLink <- get_link(searchTerm)
print(firstLink)
#this_row <- data.frame(value, firstLink)
#names(this_row)<-c("Company Name", "Website")
#data_now <- rbind(data_now, this_row)
}
get_link 是先前定义的函数。 如果 companyName 是
1
1 a
2 3
3 b
4 2
然后打印搜索词打印
[1] a
[2] 3
[3] b
[4] 2
正如预期的那样。但 打印第一个链接只打印
[1] get_link("a")
,当我想要它打印时
[1] get_link("a")
[2] get_link("3")
[3] get_link("b")
[4] get_link("2")
我正在使用来自以下答案 https://stackoverflow.com/a/57441619/14084227 的 get_first_google 链接代码 代码是:
get_first_google_link <- function(name, root = TRUE) {
url = URLencode(paste0("https://www.google.com/search?q=",name))
page <- xml2::read_html(url)
# extract all links
nodes <- rvest::html_nodes(page, "a")
links <- rvest::html_attr(nodes,"href")
# extract first link of the search results
link <- links[startsWith(links, "/url?q=")][1]
# clean it
link <- sub("^/url\\?q\\=(.*?)\\&sa.*$","\\1", link)
# get root if relevant
if(root) link <- sub("^(https?://.*?/).*$", "\\1", link)
link
}
为什么它没有按预期运行? 上面概述了期望。我正在使用 r。我已经展示了来自 rstudio 的控制台。有人可以帮忙吗?
【问题讨论】:
-
获取 get_link 函数的内容会有所帮助。
-
get_link 是我上面添加的 get_first_google_link 代码
标签: r dataframe for-loop data.table