我正在嘗試使用rvest. 但是,我通過的鏈接html_attr("href")不完整。不幸的是,鏈接的初始部分以我無法理解的方式跨頁面更改。不知道有沒有解決辦法?謝謝你。
這是該網站的兩個示例。跨頁面變化的部分似乎是“/sk####”。(我對Relazione和Testo articoli頁面的鏈接感興趣。
http://leg14.camera.it/_dati/leg14/lavori/stampati/sk5000/frontesp/4543.htm
http://leg14.camera.it/_dati/leg14/lavori/stampati/sk4500/frontesp/4477.htm
df <- structure(list(date = c(20010618L, 20010618L, 20010618L, 20010618L,
20010618L), link = c("http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=814",
"http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=858",
"http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=875",
"http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=802",
"http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=816"
)), row.names = c(NA, 5L), class = "data.frame")
df$linkfinal<- pbsapply(df$link, function(x) {
tryCatch({
x %>%
read_html() %>%
html_nodes('td td a') %>%
html_attr("href") %>%
toString()
}, error = function(e) NA)
})
uj5u.com熱心網友回復:
您只需要捕獲httr重定向url(使用),然后frontesp使用articola或替換字串relazion。如果您首先使用這些相同的子字串來測驗包含它的 href 是否存在,您可以利用 ifelse 執行上述 url 替換或回傳 NA。
如果處理大量行,則有更快的方法來應用函式。在這里閱讀后,我只是對這種方法感興趣:https : //blog.az.sg/posts/map-and-walk/。
library(tidyverse)
library(httr)
df <- structure(list(date = c(
20010618L, 20010618L, 20010618L, 20010618L,
20010618L
), link = c(
"http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=814",
"http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=858",
"http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=875",
"http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=802",
"http://leg14.camera.it/_dati/leg14/lavori/schedela/trovastampatopdl.asp?pdl=816"
)), row.names = c(NA, 5L), class = "data.frame")
get_link <- function(url, page, url_sub_string) {
link <- page %>%
html_element(sprintf("[href*=%s]", url_sub_string)) %>%
html_attr("href")
link <- ifelse(is.na(link), link, gsub("frontesp", url_sub_string, url))
return(link)
}
df <- df %>%
pmap_dfr(function(...) {
current <- tibble(...)
r <- GET(current$link)
page <- r %>% read_html()
redirect_link <- r$url
current %>%
mutate(
articola = get_link(redirect_link, page, "articola"),
relazion = get_link(redirect_link, page, "relazion")
)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377783.html
