【问题标题】:How to get text from tooltip with no attributes using Selenium Webdriver with Python?如何使用 Selenium Webdriver 和 Python 从工具提示中获取没有属性的文本?
【发布时间】:2017-04-12 22:01:43
【问题描述】:

我有一个带有工具提示的 Web 元素,它显示以下消息: ● 客户账簿收入 20,966,618 美元

该工具提示的 HTML 代码如下。我可以使用 Selenium Webdriver 将鼠标悬停在 Web 元素上,这使工具提示可见,但我不知道如何从中获取文本。有人可以帮忙吗?

<div class="highcharts-tooltip" style="position: absolute; left: 755px; top: 0px; display: block; opacity: 1; pointer-events: none; visibility: visible;">
    <span style="position: absolute; font-family: "Roboto",sans-serif; font-size: 12px; white-space: nowrap; color: rgb(51, 51, 51); margin-left: 0px; margin-top: 0px; left: 0px; top: 0px;">
        <div class="client-rate-bench-chart">
            <table class="table rdo-table-tooltip">
                <tbody>
                    <tr>
                        <td>
                            <span style="color:rgba(45,108,162,1)">●</span>
                           Client Book Revenue
                        </td>
                        <td> $20,966,618 </td>
                    </tr>
                </tbody>
           </table>
        </div>
    </span>
</div>

【问题讨论】:

    标签: python selenium selenium-webdriver


    【解决方案1】:

    你可以抢桌子,然后抢&lt;tr&gt;的第一个实例

    from bs4 import BeautifulSoup
    from selenium import webdriver
    
    driver = webdriver.Firefox()
    driver.get(URL)
    html = driver.page_source # this is how you get the HTML
    
    soup = BeautifulSoup(html)
    table = soup.find('table', class_='rdo-table-tooltip')
    tooltip = table.find('tr')
    text = tooltip.text
    

    text 将有很多额外的空白,因为 HTML 是如何格式化的,但您可以将其去掉 - 只需拆分所有空白,然后像这样重新加入元素

    final_text = ' '.join(text.split())
    print final_text
    # ● Client Book Revenue $20,966,618
    

    对于多个&lt;tr&gt;s,您可以使用.find_all('tr'),然后使用列表推导来获取行内容的列表。它看起来像这样

    soup = BeautifulSoup(html)
    table = soup.find('table', class_='rdo-table-tooltip')
    tooltips = table.find_all('tr')
    text = [' '.join(tooltip.text.split()) for tooltip in tooltips]
    

    那么 text 将是一个字符串列表,其中包含来自每个 &lt;tr&gt; 的文本

    【讨论】:

    • 如何使用 Selenium 获取与工具提示相关的 HTML 代码以将其与 BeautifulSoup 一起使用?
    • 漂亮!谢谢!我收到一条错误消息,说我应该将 soup = BeautifulSoup(html) 更改为 soup = BeautifulSoup(html, "html.parser"),但在我这样做之后,一切正常。
    • 是的,这实际上只是一个警告,您可以完全忽略它,一切都将按预期工作。
    • 如果我在 下有三个 ,您能否建议如何更改您的代码?所以我在工具提示中有三行文本,需要的结果是三个字符串变量。
    • 您可以使用.find_all('tr') 为您提供表格行的列表,然后使用列表推导从每个行中提取文本。我已经更新了答案以反映如何做到这一点。
    【解决方案2】:

    作为替代方案,您可以使用 re.findall 返回标签之间的所有文本实例。这将涉及之后的一些清理工作,但我发现在使用 Selenium 时它通常非常方便。

    import re
    
    tooltips = re.findall('<tr>(.*?)<tr>', html.replace('\n', ''))
    
    for tooltip in tooltips:
        print tooltip
    

    【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签