【问题标题】:In R, website read with read_html is redirected. How to get the url that it was redirected to?在 R 中,使用 read_html 读取的网站被重定向。如何获取它被重定向到的 url?
【发布时间】:2020-09-30 17:43:02
【问题描述】:
this_page = read_html("https://apu.edu/athletics")

> this_page
{xml_document}
<html id="ctl00_html" lang="en" class=" index homepage">
[1] <head>\n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n<script>window.client_hostname = "athletics.apu.edu";window.server_name = "79077 ...
[2] <body>\n<div style="position: fixed; left: -10000px"><script src="//cdn.blueconic.net/azusa.js" async=""></script></div>\n<script>(function(i,s,o,g,r,a,m){i[ ...

虽然我们读取了https://apu.edu/athletics,但它重定向到athletics.apu.edu。在浏览器中都是如此,也可以在this_page 的输出中看到:&lt;script&gt;window.client_hostname = "athletics.apu.edu"; ...

是否可以从this_page 变量中提取此值?

编辑:目前排名前 3 的答案(ekoam、David、Allan)都有效,并且都需要相同的时间(0.35 秒)。我接受了trace_redirects 的答案,因为它提供了所有重定向的附加信息...

【问题讨论】:

  • 不确定rvest 是否可以做到这一点。应该可以使用selenium,入门请参阅this
  • 为什么不只是read_html("https://athletics.apu.edu")
  • @ekoam 我收到了一长串 URL。提供了apu.edu/athletics,但没有提供athletics.apu.edu

标签: r web-scraping rvest xml2


【解决方案1】:

如果您不介意为此使用httr,那么只需:

httr::GET("https://apu.edu/athletics")[["url"]]

> httr::GET("https://apu.edu/athletics")[["url"]]
[1] "https://athletics.apu.edu/"

【讨论】:

    【解决方案2】:

    如果你想得到所有的重定向(这里实际上是被重定向了两次),你可以使用这个函数:

    trace_redirects <- function(url) {
      httr::GET(url)$all_headers %>%
        lapply(function(x) x$headers$location) %>%
        unlist() %>%
        unique()
    }
    

    所以你可以这样做:

    trace_redirects("https://apu.edu/athletics")
    #> [1] "https://www.apu.edu/athletics" "http://athletics.apu.edu"      
    #> [3] "https://athletics.apu.edu/"
    

    【讨论】:

      【解决方案3】:

      如果您改用html_session(),它应该可以工作:

      library(rvest)
      
      url <- "https://apu.edu/athletics"
      s <- html_session(url)
      s
      #> <session> https://athletics.apu.edu/
      #>   Status: 200
      #>   Type:   text/html; charset=utf-8
      #>   Size:   221620
      
      s$url
      #> [1] "https://athletics.apu.edu/"
      

      【讨论】:

      • 这看起来很有希望
      猜你喜欢
      • 2022-12-16
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 2018-10-19
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      相关资源
      最近更新 更多