【问题标题】:Python Selenium: Extracting dynamic tables from nested classesPython Selenium:从嵌套类中提取动态表
【发布时间】:2020-07-21 20:55:18
【问题描述】:

我正在尝试从两个表中检索数据,这些表的数据每0.5 秒更新一次,该表存在于嵌套类结构中。我使用了 Selenium 的driver.find_element_by_xpath 并试图通过div[contains(@class,one)]/div[contains(@class,two)]... 的序列获取数据,但徒劳无功。

我尝试了它的其他可用方法并搜索了其他资源,但无法接近。

任何线索!这是 HTML 代码:

<body>
<div class="one"> 
    <div class="two">
        <div class="three">

            <!--- First table -->

            <table class="Jan">
                <thread>...</thread>
                <tbody>
                    <tr>
                        <td class='cost'>100 </td>
                    </tr>
                    <tr>
                        <td class='cost'>86 </td>
                    </tr>
                    .
                    .
                    .
                    <tr>
                        <td class='cost'>56 </td>
                    </tr>           
                </tbody>
                <tfoot>...</tfoot>
            </table>

            <!--- Second table -->

            <table class="Feb">
                <thread>...</thread>
                <tbody>
                    <tr>
                        <td class='cost'>-856 </td>
                    </tr>
                    <tr>
                        <td class='cost'>-8986 </td>
                    </tr>
                    .
                    .
                    .
                    <tr>
                        <td class='cost'>-9856 </td>
                    </tr>           
                </tbody>
                <tfoot>...</tfoot>
            </table>
        </div>
    </div>
</div>

【问题讨论】:

    标签: python html selenium css-selectors


    【解决方案1】:

    您可以像这样创建类名列表,然后迭代以查找表行数,然后获取文本。

    listclass=['Jan','Feb']

    代码

    listclass=['Jan','Feb']
    for item in listclass:
        tablerows=driver.find_elements_by_xpath("//table[@class='"+ item + "']/tbody/tr")
        data=[row.get_attribute("textContent") for row in tablerows]
        print(data)
    

    在列表中输出:

    ['100', '86', '56']
    ['-856', '-8986', '-9856']
    

    您可以使用 pandas 和 read_html() 并将数据加载到 dataframe 的另一个选项。

    代码

    driver.get("url here")
    time.sleep(3)
    page=driver.page_source
    dfs=pd.read_html(page)
    
    for df in dfs:
        print(df.T)
    

    控制台输出:

         0   1   2
    0  100  86  56
         0     1     2
    0 -856 -8986 -9856
    

    【讨论】:

    • 嘿!感谢您的输入。我尝试了第一种方法,我收到NoSuchWindowException: Message: no such window: window was already closed 错误。是不是因为数据已经在短时间内发生了变化?
    • 您需要等待数据正确加载。等待加载数据。您再做一件事来检查表格元素上方是否有 iframe?
    • 你能分享你的网址吗?
    • 该 URL 在我的帐户内部。没有 iframe。数据原样。让我再过一遍。我会更新你的。
    • @meW : 刚刚更新了for loop 而不是我更新的文本get_attribute("textContent") 你现在可以查看吗?
    猜你喜欢
    • 1970-01-01
    • 2020-11-28
    • 2011-04-04
    • 2022-01-05
    • 1970-01-01
    • 2021-03-06
    • 2018-03-23
    • 2021-06-25
    • 1970-01-01
    相关资源
    最近更新 更多