【问题标题】:How to get google search results如何获取谷歌搜索结果
【发布时间】:2015-12-29 14:23:21
【问题描述】:

我使用了以下代码:

library(XML)
library(RCurl)
getGoogleURL <- function(search.term, domain = '.co.uk', quotes=TRUE) 
    {
    search.term <- gsub(' ', '%20', search.term)
    if(quotes) search.term <- paste('%22', search.term, '%22', sep='') 
        getGoogleURL <- paste('http://www.google', domain, '/search?q=',
        search.term, sep='')
    }

    getGoogleLinks <- function(google.url) 
    {
       doc <- getURL(google.url, httpheader = c("User-Agent" = "R(2.10.0)"))
       html <- htmlTreeParse(doc, useInternalNodes = TRUE, error=function(...){})
       nodes <- getNodeSet(html, "//a[@href][@class='l']")
       return(sapply(nodes, function(x) x <- xmlAttrs(x)[[1]]))
    }

search.term <- "cran"
quotes <- "FALSE"
search.url <- getGoogleURL(search.term=search.term, quotes=quotes)

links <- getGoogleLinks(search.url)

我想找到我的搜索产生的所有链接,我得到以下结果:

> links
list()

如何获取链接? 另外我想获取google搜索结果的头条和摘要如何获取呢? 最后,有没有办法获取 ChillingEffects.org 结果中的链接?

【问题讨论】:

标签: r hyperlink rcurl


【解决方案1】:

如果查看html变量,可以看到搜索结果链接都嵌套在&lt;h3 class="r"&gt;标签中。

尝试将您的getGoogleLinks 函数更改为:

getGoogleLinks <- function(google.url) {
   doc <- getURL(google.url, httpheader = c("User-Agent" = "R
                                             (2.10.0)"))
   html <- htmlTreeParse(doc, useInternalNodes = TRUE, error=function
                          (...){})
   nodes <- getNodeSet(html, "//h3[@class='r']//a")
   return(sapply(nodes, function(x) x <- xmlAttrs(x)[["href"]]))
}

【讨论】:

  • 嗨,我做同样的事情,但我的节点等于 NULL。有什么问题?谢谢!
  • 能否请您解释一下如何选择“//h3[@class='r']//a”,基于什么?
  • Google 更改了他们的网站,因此结果不再嵌套在 h3 标签中。查找节点时,"//h3[@class='r']//a" 表示查找嵌套在 'h3' 节点(即 3 级标头)中任何位置的 'a' 节点(即链接)节点,类 3文档中的任何位置。
【解决方案2】:

我创建了这个函数来读取公司名称列表,然后获取每个公司名称的顶级网站结果。它将帮助您入门,然后您可以根据需要进行调整。

#libraries.
library(URLencode)
library(rvest)

#load data
d <-read.csv("P:\\needWebsites.csv")
c <- as.character(d$Company.Name)

# Function for getting website.
getWebsite <- function(name)
{
    url = URLencode(paste0("https://www.google.com/search?q=",name))

    page <- read_html(url)

    results <- page %>% 
      html_nodes("cite") %>% # Get all notes of type cite. You can change this to grab other node types.
      html_text()

    result <- results[1]

    return(as.character(result)) # Return results if you want to see them all.
}

# Apply the function to a list of company names.
websites <- data.frame(Website = sapply(c,getWebsite))]

【讨论】:

  • 你好布莱斯先生。我写了一个程序,从你的程序中汲取灵感。但我得到字符 0。请帮助。
  • r_h = read_html("google.com/…) ; d = r_h %>% html_nodes(".iUh30") %>% html_text() %>% as.character()
  • @Therii 也许我的回答会有所帮助
【解决方案3】:

这里的其他解决方案对我不起作用,这是我对 @Bryce-Chamberlain 的问题的看法,该问题在 2019 年 8 月对我有用,它还回答了另一个封闭的问题:company name to URL in R


# install.packages("rvest")

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
}

companies <- data.frame(company = c("apple acres llc","abbvie inc","apple inc"))
companies <- transform(companies, url = sapply(company,get_first_google_link))
companies
#>           company                            url
#> 1 apple acres llc https://www.appleacresllc.com/
#> 2      abbvie inc        https://www.abbvie.com/
#> 3       apple inc         https://www.apple.com/

reprex package (v0.2.1) 于 2019-08-10 创建

【讨论】:

    【解决方案4】:

    免费解决方案不再有效。此外,它不允许您搜索您所在位置以外的区域。这是使用 Google 自定义搜索 API 的解决方案。 API 允许每天 100 次免费 API 调用。以下函数仅返回 10 个结果或第 1 页。1 次 API 调用仅返回 10 个结果。

    Google.Search.API <- function(keyword, google.key, google.cx, country = "us")
    {
      # keyword = keywords[10]; country = "us"
      url <- paste0("https://www.googleapis.com/customsearch/v1?"
                    , "key=", google.key
                    , "&q=", gsub(" ", "+", keyword)
                    , "&gl=", country         # Country
                    , "&hl=en"                # Language from Browser, english
                    , "&cx=", google.cx
                    , "&fields=items(link)"
                    )
    
      d2 <- url %>%
            httr::GET(ssl.verifypeer=TRUE) %>%
            httr::content(.) %>% .[["items"]] %>%
            data.table::rbindlist(.) %>%
            mutate(keyword, SERP = row_number(), search.engine = "Google API") %>%
            rename(source = link) %>%
            select(search.engine, keyword, SERP, source)
    
      pause <- round(runif(1, min = 1.1, max = 5), 1)
      if(nrow(d2) == 0)
      {cat("\nPausing", pause, "seconds. Failed for:", keyword)} else
      {cat("\nPausing", pause, "seconds. Successful for:", keyword)}
    
      Sys.sleep(pause)
      rm(keyword, country, pause, url, google.key, google.cx)
      return(d2)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      • 2011-05-21
      • 1970-01-01
      • 1970-01-01
      • 2012-04-10
      • 2014-08-25
      • 2015-07-27
      相关资源
      最近更新 更多