【问题标题】:How to select "href" of a web page of a specific "target"?如何选择特定“目标”的网页的“href”?
【发布时间】:2021-12-05 09:11:27
【问题描述】:
<a class="image teaser-image ng-star-inserted" target="_self" href="/politik/inland/neuwahlen-2022-welche-szenarien-jetzt-realistisch-sind/401773131">

我只是想提取“href”(例如上面的HTML标签)以便将它与本网站的域名“https://kurier.at”连接起来" 和网页抓取首页上的所有文章。

我尝试了以下代码

library(rvest)
library(lubridate)


kurier_wbpg <- read_html("https://kurier.at")

# I just want the "a" tags which come with the attribute "_self" 

articleLinks <- kurier_wbpg %>% html_elements("a")%>%
html_elements(css = "tag[attribute=_self]")  %>% 
html_attr("href")%>% 
paste("https://kurier.at",.,sep = "")

当我执行到上面代码块的 html_attr("href") 部分时,我得到的结果是

character(0)

我认为选择 HTML 元素标签有问题。 我需要这方面的帮助吗?

【问题讨论】:

    标签: r web-scraping href rvest html-target


    【解决方案1】:

    您需要将 css 缩小到第二个预告块图像,您可以通过使用类的命名约定来做到这一点。您可以使用url_absolute() 添加域。

    library(rvest)
    library(magrittr)
    
    url <- 'https://kurier.at/'
    result <- read_html(url) %>% 
      html_element('.teasers-2 .image') %>% 
      html_attr('href') %>% 
      url_absolute(url)
    

    获取所有预告片的原则相同:

    results <- read_html(url) %>% 
      html_elements('.teaser .image') %>% 
      html_attr('href') %>% 
      url_absolute(url)
    

    不确定是否要包含 5 个底部的块。如果是这样,您可以再次使用类

    articles <- read_html(url) %>% 
      html_elements('.teaser-title') %>% 
      html_attr('href') %>% 
      url_absolute(url)
    

    【讨论】:

    • 非常感谢您提出“使用类的命名约定”,我现在正在调查。我用了.teaser-title,出现了9个文章链接。但是当我检查“SelectorGadget”chrome 扩展时,应该有 132 个带有标签“.teaser-title”的文章链接
    • JavaScript 在浏览器中运行时动态添加的。
    • 再次感谢您的进一步解释,我会尝试这种方法。这样我可以提取不同标签下的 URL,但最后,我必须创建一个 URL 列表,以便将它们提供给我用来提取每篇文章的日期的 for 循环。
    【解决方案2】:

    它适用于xpath -

    library(rvest)
    
    kurier_wbpg <- read_html("https://kurier.at")
    
    articleLinks  <- kurier_wbpg %>% 
      html_elements("a") %>%
      html_elements(xpath = '//*[@target="_self"]') %>%
      html_attr('href') %>%
      paste0("https://kurier.at",.)
    
    articleLinks
    
    # [1] "https://kurier.at/plus"
    # [2] "https://kurier.at/coronavirus"
    # [3] "https://kurier.at/politik"
    # [4] "https://kurier.at/politik/inland"
    # [5] "https://kurier.at/politik/ausland"
    #...
    #...
    

    【讨论】:

    • 非常感谢 Ronak 的支持,我尝试了 XPath 并获得了文章的链接以及与 109、110、112、114 等文章无关的链接,如下所示在结果中。 \n [109] "https://kurier.at/chronik" ,[110] "https://kurier.at/chronik/oberoesterreich" ,[112] "https://kurier.at/wirtschaft",[114] "https://kurier.at/" \n 现在我将不得不寻找一种方法来清理它并获取文章链接。我了解通过您的回答在“target = _self”属性下获取文本的方式再次感谢
    猜你喜欢
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 2016-03-28
    • 2018-02-10
    相关资源
    最近更新 更多