You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R语言readLines()读取网页报错:无法打开连接求协助

解决R读取Google Scholar网页连接失败的问题

问题原因

Google Scholar会对请求做验证,默认的R网络请求没有携带**用户代理(User-Agent)**标识,被服务器判定为非浏览器请求而拦截,导致无法建立连接。

解决方案

方法1:使用httr包(推荐)

httr是R中处理HTTP请求更便捷的工具,支持自定义请求头:

# 首次使用先安装包
install.packages("httr")
library(httr)

# 设置模拟浏览器的User-Agent
ua <- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
response <- GET("https://scholar.google.com/citations?user=HI-I6C0AAAAJ&hl=en", user_agent(ua))

# 提取网页文本内容
htmlCode <- content(response, "text")

方法2:给readLines()添加请求头

如果坚持使用readLines(),可以通过url()的headers参数设置User-Agent:

connection <- url(
  "https://scholar.google.com/citations?user=HI-I6C0AAAAJ&hl=en",
  headers = list(
    "User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
  )
)
htmlCode <- readLines(con = connection)
close(connection) # 记得读取后关闭连接

方法3:调整RCurl的请求设置

使用RCurl时,同样需要指定User-Agent:

library(RCurl)
ua <- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
htmlCode <- getURL(
  "https://scholar.google.com/citations?user=HI-I6C0AAAAJ&hl=en",
  useragent = ua
)

注意事项

  • User-Agent可以根据自己常用的浏览器调整,也能在浏览器开发者工具中查看真实的User-Agent值
  • Google Scholar的反爬机制可能会更新,若后续再次出现问题,可更换User-Agent或使用rvest包(基于httr封装,更适合网页解析)

内容的提问来源于stack exchange,提问作者JereW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:25:44