【问题标题】:How to get all valid urls from website?如何从网站获取所有有效的网址?
【发布时间】:2017-08-09 23:19:13
【问题描述】:

我正在做一个this website 的网络抓取项目。

此时我想做的是从这样的网址中抓取艺术家姓名:https://lsdb.eu/artists/view/225/

由于艺术家的编号设置为 225,因此该页面存在。但是,https://lsdb.eu/artists/view/226/ 不存在,但确实存在编号大于 226 的页面。

有什么方法可以抓取网站以查看哪些https://lsdb.eu/artists/view/xxx/ 网址有效?

【问题讨论】:

  • 你可以在try 内包装刮擦,这样它就可以跳过错误的网址并转到下一个。或者,httr::GET 允许访问站点响应,因此 GET("https://lsdb.eu/artists/view/225/")$status_code 将返回 200(好),而 GET("https://lsdb.eu/artists/view/226/")$status_code 将返回 404(坏)

标签: html r web-scraping rvest httr


【解决方案1】:

站点响应 HTTP HEAD 请求,这通常对站点更友好,因为它们通常占用更少的资源(至少不返回任何内容,因此可以节省时间和带宽)。您可以执行以下操作:

library(httr)

is_valid_artist <- function(x) {
  httr::status_code(httr::HEAD(sprintf("https://lsdb.eu/artists/view/%s/", x)))
}

is_valid_artist("225")
## [1] 200

is_valid_artist("226")
## [1] 404 

is_valid_artist("42437")
## [1] 200

is_valid_artist("100000000")
## [1] 404

如果您选择进行一系列顺序查找,请在请求之间添加一些暂停,因为您仍然可以对站点进行 DoS。对于完整的内容,建议拉取 5-10 秒,但对于 HEAD 请求,您可以在道德上将其拉到 1 秒 (IMO)。

【讨论】:

    猜你喜欢
    • 2013-12-04
    • 2013-02-24
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    相关资源
    最近更新 更多