在read_html函数中添加user_agent解决浏览器过时检测问题
解决爬取PGATour表格时的浏览器过时检测问题
问题原因分析
你遇到的问题主要来自三个方面:
read_html参数写法错误:原代码中read_html(, user_agent = "...")里的多余逗号导致UA参数传递异常,设置并未生效。- UA版本过于老旧:你使用的Chrome 89版本UA字符串已被网站判定为过时浏览器,无法绕过检测。
- 缺少必要请求头:仅设置UA可能不够,部分网站会校验
Accept、Accept-Language等其他请求头来判断是否为真实浏览器。
修正后的解决方案
方案1:修正read_html的UA写法并更新UA版本
直接修正参数格式,同时替换为较新的浏览器UA字符串:
#Scrape function get_info <- function(link, tournament) { link %>% # 去掉多余逗号,更新为2024年主流Chrome版本UA read_html(user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36") %>% html_table() %>% .[[1]] %>% clean_names() %>% mutate(tournament = tournament) }
方案2:使用httr显式发送请求(更稳定)
通过httr包手动构造完整请求头,模拟真实浏览器的请求行为,这种方式可控性更强,能应对更严格的反爬检测:
library(dplyr) library(tidyverse) library(janitor) library(rvest) library(magrittr) library(purrr) library(openxlsx) library(httr) # 新增httr包用于构造请求 #leaderboard links df6 <- expand.grid( tournament_id = c("the-american-express","wm-phoenix-open","farmers-insurance-open"), year_id = c("2004", "2005", "2006") ) %>% mutate( links = paste0( 'https://www.pgatour.com/tournaments/', tournament_id, "/past-results.", year_id, '.html' ) ) %>% as_tibble() #Scrape function get_info <- function(link, tournament) { # 构造完整请求头,模拟真实浏览器请求 response <- GET( url = link, user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"), add_headers( "Accept" = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Language" = "en-US,en;q=0.5", "Upgrade-Insecure-Requests" = "1" ) ) # 解析响应并处理表格 response %>% content(as = "parsed") %>% html_table() %>% .[[1]] %>% clean_names() %>% mutate(tournament = tournament) } #retrieve data test501 <- df6 %>% mutate(tables = map2(links, tournament_id, possibly(get_info, otherwise = tibble()))) test501 <- test501 %>% unnest(everything()) test501
额外建议
- 添加请求延迟:在
get_info函数中加入Sys.sleep(1),避免短时间内发送大量请求导致IP被封禁。 - 检查网站规则:确认目标网站的robots.txt允许爬取相关内容,避免违反网站使用条款。
内容的提问来源于stack exchange,提问作者DonnyDolio
相关产品推荐
相关产品推荐

