gpt4 book ai didi

r - 基于 IIS 的网站的网页抓取

转载 作者:行者123 更新时间:2023-12-02 01:31:43 24 4
gpt4 key购买 nike

我正在使用 R 从 this site 中抓取表格.

我正在使用库rvest

#install.packages("rvest", dependencies = TRUE) 
library(rvest)
OPMpage <- read_html("https://www.opm.gov/policy-data-oversight/data-analysis-documentation/federal-employment-reports/historical-tables/total-government-employment-since-1962/")

我收到此错误:

Error in open.connection(x, "rb") : HTTP error 403.

我做错了什么?

最佳答案

这是 forbidding you无法访问该页面,因为 header 的 user-agent 字符串中有 NULL。 (通常它是一个字符串,告诉您正在使用的浏览器,尽管有些浏览器允许用户欺骗其他浏览器。)使用 httr 包,您可以设置一个 user-agent 字符串:

library(httr)
library(rvest)

url <- "https://www.opm.gov/policy-data-oversight/data-analysis-documentation/federal-employment-reports/historical-tables/total-government-employment-since-1962/"

x <- GET(url, add_headers('user-agent' = 'Gov employment data scraper ([[your email]])'))

封装在 GET 请求中,add_headers 允许您设置您喜欢的任何参数。如果您只想设置的话,您还可以使用更具体的 user_agent 函数来代替 add_headers

在这种情况下,任何 user-agent 字符串都可以使用,但有礼貌的是(请参阅最后的链接)说明您是谁以及您想要什么。

现在您可以使用 rvest 解析 HTML 并提取表格。您需要一种方法来选择相关表;查看 HTML,我看到它有 class = "DataTable",但您也可以使用 SelectorGadget(请参阅 rvest 小插图)来查找有效的 CSS 或 XPath 选择器。因此

x %>% 
read_html() %>%
html_node('.DataTable') %>%
html_table()

给你一个漂亮的(如果不是完全干净的)数据框架。

注意:负责任且合法地进行抓取。鉴于 OPM 是政府来源,因此它属于公共(public)领域,但很多网络的情况并非如此。请务必阅读任何服务条款,加上 this nice post on how to scrape responsibly.

关于r - 基于 IIS 的网站的网页抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35690914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com