r - 在 R 中从 opensubtitles.org 网页抓取字幕

标签 r web-scraping

我是网络抓取新手,目前正在尝试为一个研究项目下载超过 100,000 部电影的字幕文件。每部电影都有一个唯一的 IMDb ID(即《盗梦空间》的 ID 为 1375666)。我在 R 中有一个包含 102524 个 ID 的列表,我想从 opensubtitles.org 下载相应的字幕。

每部电影在网站上都有自己的页面,例如,《盗梦空间》有:

https://www.opensubtitles.org/en/search/sublanguageid-eng/imdbid-1375666

通过单击名为“电影名称”的表中的第一个链接来获取下载字幕的链接,该链接会将您带到一个新页面,然后单击该页面上的“下载按钮”。

我正在使用 rvest 来抓取页面,并且我编写了以下代码:

for(i in 1:102524) {
  subtitle.url = paste0("https://www.opensubtitles.org/en/search/sublanguageid-eng/imdbid-", movie.ids[i])

  read_html(subtitle.url) %>%
    html_nodes(".head+ .expandable .bnone")
  # Not sure where to go from here
}

任何有关如何执行此操作的帮助将不胜感激。

编辑:我知道我问的问题非常复杂,但是任何关于从哪里开始的指示都会很棒。

最佳答案

通过链接和下载按钮,我们可以看到实际的字幕文件是从https://www.opensubtitles.org/en/download/vrf-108d030f/sub/6961922下载的(以你为例)。我在下载时检查 Mozilla 的开发者工具中的Network选项卡时发现了这一点。

我们可以使用以下方法直接从该地址下载:

    download.file('https://www.opensubtitles.org/en/download/vrf-108d030f/sub/6961922', 
              destfile = 'subtitle-6961922.zip')

据我所知,所有下载的基本网址(https://www.opensubtitles.org/en/download/vrf-108d030f/sub/)都是固定的,所以我们只需要网站的 ID。

在搜索页面中找到 ID,执行以下操作:

id <- read_html(subtitle.url) %>%
    html_node('.bnone') %>% 
    html_attr('href') %>% 
    stringr::str_extract('\\d+')

所以,把它们放在一起:

search_url <- 'https://www.opensubtitles.org/en/search/sublanguageid-eng/imdbid-'
download_url <- 'https://www.opensubtitles.org/en/download/vrf-108d030f/sub/'

for(i in 1:102524) {
    subtitle.url = paste0(search_url, movie.ids[i])

    id <- read_html(subtitle.url) %>%
        html_node('.bnone') %>% 
        html_attr('href') %>% 
        stringr::str_extract('\\d+')

    download.file(paste0(download_url, id), 
                  destfile = paste0('subtitle-', movie.ids[i], '.zip'))

    # Wait somwhere between 1 and 4 second before next download
    # as courtesy to the site
    Sys.sleep(runif(1, 1, 4))
}

请记住,这将需要很长时间!

关于r - 在 R 中从 opensubtitles.org 网页抓取字幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44542519/

相关文章:

python - 无法使用selenium从页面中名为 'heading'的每个类获取数据

arrays - Array .push 在每个循环内返回用相同对象填充的数组

读取固定宽度数据而不换行

r - 使用 Xaringan 时 custom.css 消失

r - 根据函数的输入动态创建 Rmd 文件

python - 如何从字典列表中提取数据到 pandas 数据框中?

python - 在代理服务器后面运行 selenium

r - 如何在 R 中将单个数字与矩阵绑定(bind)

r - 用 R 绘制决策树

javascript - Scrapy 之类的 Nodejs 工具?