【问题标题】:how to extract text from anchor tag inside div class in r如何从r中的div类中的锚标记中提取文本
【发布时间】:2017-05-16 22:00:41
【问题描述】:

我正在尝试从嵌入在 div 标签中的锚标签中获取文本。以下是网站链接`http://mmb.moneycontrol.com/forum-topics/stocks-1.html

我要提取的文字是Mawana Sugars

<a href="/forum-topics/stocks/mawana-sugars-245010.html" class="op_bld16 anch_pb7">Mawana Sugars</a>

所以我想提取该网站上列出的所有股票名称及其描述。

这是我在 R 中的尝试

doc <- htmlParse("http://mmb.moneycontrol.com/forum-topics/stocks-1.html")
xpathSApply(doc,"//div[@class='clearfix PR PB5']//text()",xmlValue)

但是,它不返回任何东西。我如何在 R 中做到这一点?

【问题讨论】:

    标签: r


    【解决方案1】:

    我的回答和我刚才给here的回答基本一样。

    数据是动态加载的,不能直接从html中获取。但是,以 Chrome DevTools 中的“网络”为例,我们可以在 http://mmb.moneycontrol.com/index.php?q=topic/ajax_call&section=get_messages&offset=&lmid=&isp=0&gmt=cat_lm&catid=1&pgno=1 找到格式良好的 JSON

    让您开始:

    library(jsonlite)
    dat <- fromJSON("http://mmb.moneycontrol.com/index.php?q=topic/ajax_call&section=get_messages&offset=&lmid=&isp=0&gmt=cat_lm&catid=1&pgno=1")
    

    输出如下:

    dat[1:3, c("msg_id", "user_id", "topic", "heading", "flag", "price", "message")]
    #     msg_id      user_id    topic  heading flag
    # 1 47730730    liontrade     NMDC   Stocks  APR
    # 2 47730726 agrawalknath Glenmark Glenmark  APR
    # 3 47730725      bissy91  Infosys   Stocks  APR
    #                                                  price
    # 1 Price when posted :  BSE: Rs. 127.90 NSE: Rs. 128.15
    # 2                 Price when posted :  NSE: Rs. 714.10
    # 3 Price when posted :  BSE: Rs. 956.50 NSE: Rs. 955.00
    #                                                                                                                        message
    # 1                                                                         There is no mention of dividend in the announcement.
    # 2                        Eagerly Waiting for 670 to 675 to BUY second phase of Buying in Cash Delivery. Already Holding @ 800.
    # 3 6 ✂ ✂--Don t Pay High Brokerage While Trading. Take Delivery Free & Rs 20 to trade in any size - Join Today .? goo.gl/hDqLnm
    

    【讨论】:

    • 非常感谢您的回答。就一个问题,你是怎么提取那个链接的?
    • 我打开了 Chrome DevTools (Ctrl + Shift + I) 并查看了网络选项卡,然后按 F5 并按 Type 排序以过滤掉图像等。有时您要查找的内容可以直接在Sources 选项卡中找到
    • 知道了.. 如果我想提取该网站上的小部件文本怎么办?
    • 如果是Flash,我知道没有简单的方法。如果是 JS,如果你能找到小部件调用的数据源,那就“容易”了,就像这里。否则,一旦我使用 Selenium 编写脚本,因为我找不到更好的方法(而且它又丑又慢)
    • 在这个网站http://mmb.moneycontrol.com/ 上有一个sentifi 小部件,可以在社交媒体上显示印度股票的趋势。如何提取该文本?
    猜你喜欢
    • 2018-12-29
    • 2015-04-24
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2013-09-20
    相关资源
    最近更新 更多