gpt4 book ai didi

xml - 如何使用 R(Rcurl/XML 包)从 Yahoo 抓取选项数据?

转载 作者:行者123 更新时间:2023-12-04 06:28:08 24 4
gpt4 key购买 nike

基本上,我想每天从 Yahoo! 抓取一些选项数据!金融。我一直在用(1)作为例子踢轮胎。然而,它还没有完全解决,因为我不熟悉 HTML。

(1) Scraping html tables into R data frames using the XML package

例如,我想抓取并收集以下选项链
http://finance.yahoo.com/q/op?s=MNTA&m=2011-05

这是我迄今为止尝试过的。最后两行不起作用,因为我不清楚我应该寻找什么类(class)。任何帮助都会很棒。谢谢。

library(RCurl)
library(XML)

theurl <- "http://finance.yahoo.com/q/op?s=MNTA&m=2011-05"
webpage <- getURL(theurl)
webpage <- readLines(tc <- textConnection(webpage)); close(tc)

pagetree <- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE)

tablehead <- xpathSApply(pagetree, "//*/table[@class='yfnc_datamodoutline1']/tr/th", xmlValue)

results <- xpathSApply(pagetree, "//*/table[@class='wikitable sortable']/tr/td", xmlValue)

最后两行不要

最佳答案

我假设您想获取 Call Options 和 Put Options 两个表中的信息。这是一种使用 XML 的简单方法。包裹

url  = "http://finance.yahoo.com/q/op?s=MNTA&m=2011-05"
# extract all tables on the page
tabs = readHTMLTable(url, stringsAsFactors = F)

# locate tables containing call and put information
call_tab = tabs[[11]]
put_tab = tabs[[15]]

我通过人工检查找出了两个表的位置。如果位置在您解析的页面之间会有所不同,那么您可能需要使用表格长度或其他一些文本标准以编程方式定义位置。

编辑。您可能感兴趣的两个表都有 cellpadding = 3 .您可以使用此信息使用以下代码直接提取两个表
# parse url into html tree
doc = htmlTreeParse(url, useInternalNodes = T)

# find all table nodes with attribute cellpadding = 3
tab_nodes = xpathApply(doc, "//table[@cellpadding = '3']")

# parse the two nodes into tables
tabs = lapply(tab_nodes, readHTMLTable)
names(tabs) = c("calls", "puts")

这是一个包含两个表的列表。

关于xml - 如何使用 R(Rcurl/XML 包)从 Yahoo 抓取选项数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5774370/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com