【问题标题】:What's my user agent when I parse website with rvest package in R?当我在 R 中使用 rvest 包解析网站时,我的用户代理是什么?
【发布时间】:2015-10-03 01:59:33
【问题描述】:

由于在 R 中很容易,我使用 rvest 包来解析 HTML 以从网站中提取信息。

我想知道在请求期间我的 User-Agent 是什么(如果有的话),因为 User-Agent 已分配给 Internet 浏览器,还是有办法以某种方式设置它?

我打开会话并从 HTML 中提取信息的代码如下:

library(rvest)
se <- html_session( "http://www.wp.pl" ) %>% 
html_nodes("[data-st-area=Glonews-mozaika] li:nth-child(7) a") %>%
html_attr( name = "href" )

【问题讨论】:

  • 如果您使用任何常规 linux 发行版,这里有一个快捷方式:运行 netcat -l -p 8080 localhost | grep -i user-agent,然后创建 html_session("http:://localhost:8080")
  • 太好了。谢谢!

标签: r web-scraping rvest


【解决方案1】:

我用https://httpbin.org/user-agent查了一下:

library(rvest)
se <- html_session( "https://httpbin.org/user-agent" )
se$response$request$options$useragent

答案:

[1] "libcurl/7.37.1 r-curl/0.9.1 httr/1.0.0"

请参阅this bug report 了解覆盖它的方法。

【讨论】:

  • 谢谢,所以我用se$response$request$opts$useragent检查了这个
  • 如果你用这一行编辑你的答案:'se$response$request$opts$useragent' 我会接受它:)
  • 已编辑。我需要使用options,而不是opts。不确定您是否有错字,或者我们是否使用了不同的库版本或其他东西。
  • 很好的回应,但使用httpbin.org/user-agent 作为示例有点误导,因为它暗示这个特殊的 URL 具有魔力:事实上,任何 URL 都应该给出相同的正确结果。 example.org 是一个更好的例子,因为它是故意通用的。
  • 好点子,不过如果您查看编辑历史记录,您会发现我最初只是使用了网站的回复 (se['response'])。
【解决方案2】:

我在教程的某个地方找到了这个,它看起来是一种更简单快捷的方法:

uastring <- "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
session <- html_session("https://www.linkedin.com/job/", user_agent(uastring))

【讨论】:

  • 为此,您还需要 httr 包。
猜你喜欢
  • 2020-01-13
  • 2016-04-17
  • 2020-09-21
  • 1970-01-01
  • 2011-09-06
  • 2021-03-22
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
相关资源
最近更新 更多