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

网站能否阻止Web Scraping?我的R爬虫代码运行报错求助

爬取股票基金价格时遇到"Header without colon"错误的解决办法

问题描述

尝试爬取某公司公开的股票基金价格(无需登录),但运行R代码时出现Error in open.connection(x, "rb") : Header without colon错误。

爬取代码

library(rvest)
library(dplyr)

link <- "https://www.azvalor.com/valores-liquidativos"
page <- read_html(link)

name <- page %>% html_nodes(".sorting_1") %>% html_text()
price <- page %>% html_nodes("td:nth-child(3)") %>% html_text()
date <- page %>% html_nodes(".sorting_1+ td") %>% html_text()

stock <- data.frame(name, price, date, stringsAsFactors = FALSE)

控制台报错输出

> library(rvest)
> library(dplyr)

Attaching package: ‘dplyr’

The following objects are masked from ‘package:stats’:

    filter, lag

The following objects are masked from ‘package:base’:

    intersect, setdiff, setequal, union

> 
> link <- "https://www.azvalor.com/valores-liquidativos"
> page <- read_html(link)
Error in open.connection(x, "rb") : Header without colon
>

问题分析与解决

这个错误大概率是网站反爬机制拦截了请求,或是服务器返回的响应头格式异常。read_html默认的请求头会被识别为非浏览器请求,触发反爬限制。

解决步骤

  1. 添加浏览器请求头:用httr包模拟浏览器发送请求,设置User-Agent字段,让服务器认为是正常浏览器访问。
  2. 调整后的代码示例:
library(rvest)
library(dplyr)
library(httr)

link <- "https://www.azvalor.com/valores-liquidativos"
# 设置模拟浏览器的请求头
headers <- add_headers(
  `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"
)
# 发送请求并获取响应
response <- GET(link, headers)
# 解析响应内容
page <- read_html(content(response, "text"))

name <- page %>% html_nodes(".sorting_1") %>% html_text()
price <- page %>% html_nodes("td:nth-child(3)") %>% html_text()
date <- page %>% html_nodes(".sorting_1+ td") %>% html_text()

stock <- data.frame(name, price, date, stringsAsFactors = FALSE)
  1. 其他排查方向:如果添加请求头后仍报错,可尝试:
    • 复制浏览器访问该页面时的Cookie值,添加到请求头中
    • 增加请求间隔,避免频繁访问触发反爬
    • 确认网站robots.txt是否允许爬取该页面

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 06:46:28