【问题标题】:Scraping this URL, R XML and getting siblings抓取此 URL、R XML 并获取兄弟姐妹
【发布时间】:2014-11-13 23:06:24
【问题描述】:

您好:我想取消联邦选举区 - 2003 年子表“安大略省”的代表令。网址在这里:http://www.elections.ca/content.aspx?section=res&dir=cir/list&document=index&lang=e#list

我已经尝试过这段代码,它让我很接近,但并不完全在那里。

doc<-htmlParse('http://www.elections.ca/content.aspx?section=res&dir=cir/list&document=index&lang=e#list', useInternalNodes=TRUE)
doc2<-getNodeSet(doc, "//table/caption[text()='Ontario']")

我知道我可以使用 readHTMLTable 来简单地执行此操作,只需找到特定的表,但我也想知道如何选择与 Ontario 相同的标题节点的兄弟节点。 谢谢

【问题讨论】:

    标签: xml r xpath web-scraping


    【解决方案1】:

    您可以在 XPATH 中使用 following-sibling

    library(XML)
    appURL <- 'http://www.elections.ca/content.aspx?section=res&dir=cir/list&document=index&lang=e#list'
    doc<-htmlParse(appURL, encoding = "UTF-8")
    tableNode <- doc["//*[@id='list']/following-sibling::table/caption[text()='Ontario']/.."][[1]]
    myTable <- readHTMLTable(tableNode)
    > head(myTable)
    Code          Federal Electoral Districts Population 2006
    1 35001                       Ajax–Pickering         117,183
    2 35002        Algoma–Manitoulin–Kapuskasing          77,961
    3 35003 Ancaster–Dundas–Flamborough–Westdale         111,844
    4 35004                               Barrie         128,430
    5 35005                    Beaches–East York         104,831
    6 35006                 Bramalea–Gore–Malton         152,698
    

    所以要分解 XPATH。标题 Federal Electoral Districts – Representation Order of 2003 有一个 id="list"。 HTML 中的 id 是唯一的,因此我们可以对此进行过滤

    • //*[@id='list'] 查找 id 等于“list”的节点
    • /following-sibling::table 获取所有跟随它的兄弟节点是表
    • /caption[text()='Ontario'] 选择标题为“Ontario”的节点
    • /.. 返回一个节点

    这会将所需的表节点作为列表提供给您。只有一个节点满足上述要求。然后这个节点就可以被readHTMLTable处理了。

    【讨论】:

    • 不知何故我就知道你会回答这个问题
    • @RichardScriven 很久以前,在 XPATH 存在之前,我曾经使用正则表达式来抓取 HTML。当我发现 XPATH 并且曾经相当复杂和脆弱的任务减少到几行时,我被迷住了。所以现在我总是喜欢 XPATH 难题:)。
    • 这真是太棒了,你能告诉我最好的 xpathApply 教程网站是什么吗?我不知道 following-sibling::table 语法。
    猜你喜欢
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 2019-08-21
    • 2019-08-29
    • 2012-02-27
    • 1970-01-01
    • 2019-05-06
    • 2014-04-23
    相关资源
    最近更新 更多