【问题标题】:how to parse/read a .txt webpage in R? [closed]如何在 R 中解析/读取 .txt 网页? [关闭]
【发布时间】:2020-01-24 15:44:41
【问题描述】:

我在网上找不到答案;如果这是一个重复的问题,请原谅我。

我有一列包含数千个指向 .txt 网页的链接。我想解析/阅读它们。他们里面有文本和html代码。这是一个例子:link

【问题讨论】:

  • 你可能想看看rvestpurrr
  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则会更容易为您提供帮助。
  • 这真的取决于你想用它做什么。您可以查看 XML 包,因为它看起来像是 XML。这将使其成为您可以使用的对象,但显然您将不得不做更多的工作才能将其变成可以运行分析的数据框。
  • 查看 edgarWebR 包。
  • @r2evans 因为 html 是一种 XML,这很好。 XML 包也有一些专门用于处理 html 的有用函数,例如我一直用于网络抓取的 getHTMLLinksreadHTMLTable

标签: r web-scraping


【解决方案1】:

页面包含嵌入在文本文件中的 html 文档。通过查找 HTML 标签很容易提取它们。完成后,您可以使用 lapply 命令将它们存储在所有 html 进程中的列表中

url <- paste0("https://www.sec.gov/Archives/edgar/data/1096759/",
              "000126246313000226/0001262463-13-000226.txt")

page   <- readLines(url)
start  <- grep("<HTML>", page)
finish <- grep("</HTML>", page)

htmls <- mapply(function(x, y) paste0(page[x:y], collapse = "\n"), start, finish)
lapply(htmls, function(x) read_html(x) %>% html_text()) -> result

这给出了:

cat(result[[1]])
#>     29
#>      
#>     
#> 
#> Cash and Cash Equivalents
#> 
#>  
#> 
#> Cash and cash equivalents include highly liquid investments
#> with original maturities of three months or less.
#> 
#>  
#> 
#> Foreign Currency Translation
#> 
#>  
#> 
#> The Company’s functional and
#> reporting currency is U.S. dollars. The consolidated financial statements of the Company are translated to U.S. dollars in accordance
#> with ASC 830, “Foreign Currency Matters.” Monetary assets and liabilities denominated in foreign currencies
#> are translated using the exchange rate prevailing at the balance sheet date. Gains and losses arising on translation or settlement
#> of foreign currency denominated transactions or balances are included in the determination of income. The Company has not, to the
#> date of these consolidated financial statements, entered into derivative instruments to offset the impact of foreign currency fluctuations.
### etc...

【讨论】:

    【解决方案2】:

    这真的取决于这些文件的布局是否一致,但如果它们总是在顶部有这个表,你可以这样做:

    library(XML)
    x <- readLines("https://www.sec.gov/Archives/edgar/data/1096759/000126246313000226/0001262463-13-000226.txt")
    i <- readHTMLTable(x, stringsAsFactors = FALSE)
    
    address <- i[[1]][grep("Address of principal executive offices", i[[1]][[1]]) - 1, 1]
    

    假设您的地址将始终位于页面的第一个表格中,并且地址将是显示在文本正上方的一行。它可能需要一些调整。

    【讨论】:

      猜你喜欢
      • 2010-12-23
      • 2014-02-18
      • 2021-05-24
      • 2014-09-15
      • 1970-01-01
      • 2015-02-23
      • 2023-03-12
      • 2018-03-14
      • 1970-01-01
      相关资源
      最近更新 更多