我是BeautifulSoup的新手,我想用它来提取98.2%和94.2%的元素. 我想打印:

apples: 98.2% bananas: 94.2%

我该怎么做呢?先谢谢你.

<div>
  <table class="stock">
    <tr>
      <th></th>
      <th scope="col">Equal</th>
      <th scope="col">Total</th>
      <th scope="col">Fruits</th>
    </tr>
    <tr>
      <th scope="row">apples:</th>
      <td>524</td>
      <td>525</td>
      <td class="high">98.2%</td>
    </tr>
    <tr>
      <th scope="row">pears:</th>
      <td>58</td>
      <td>58</td>
      <td class="high">100.0%</td>
    </tr>
    <tr>
      <th scope="row">bananas:</th>
      <td>165</td>
      <td>179</td>
      <td class="high">94.2%</td>
    </tr>
  </table>

最初,我try 了以下操作,但它会打印: [98.2百分之一百、百分之九十四点二]

from bs4 import BeautifulSoup
HTMLFile = open("stock.html", "r")
index = HTMLFile.read()
soup = BeautifulSoup(index, 'html.parser')
element = soup.select(".stock .high")
print(element)

推荐答案

try :

from bs4 import BeautifulSoup

html_text = """\
  <table class="stock">
    <tr>
      <th></th>
      <th scope="col">Equal</th>
      <th scope="col">Total</th>
      <th scope="col">Fruits</th>
    </tr>
    <tr>
      <th scope="row">apples:</th>
      <td>524</td>
      <td>525</td>
      <td class="high">98.2%</td>
    </tr>
    <tr>
      <th scope="row">pears:</th>
      <td>58</td>
      <td>58</td>
      <td class="high">100.0%</td>
    </tr>
    <tr>
      <th scope="row">bananas:</th>
      <td>165</td>
      <td>179</td>
      <td class="high">94.2%</td>
    </tr>
  </table>"""

soup = BeautifulSoup(html_text, "html.parser")

for tr in soup.select('tr:-soup-contains("apples", "bananas")'):
    print(tr.th.text, tr.find(class_="high").text)

打印:

apples: 98.2%
bananas: 94.2%

Html相关问答推荐

在元素之间添加空格

如何防止第二列中的内容影响第一列中内容的位置?

在CSS中旋转排除的蒙版图像

窗口视图之外的下拉菜单位置

需要帮助创建一个简单的html css网格布局

平移变换下的SVG剪辑路径行为

防止position:relative的child在出界时收缩

使用CSS Flexbox时,我的图像未对齐

禁用所有行,但在16角中单击编辑按钮的行除外

配置了 HTML 视口的 Google Apps 脚本移动网络应用程序无法正确显示

:invalid Select 器的惰性判断

UL 的行为就像它不属于任何类别

如何使用 Tailwind CSS 分隔导航栏中的元素?

jQuery 索引返回不正确的结果

在HTML请求中添加源URL

将图像高度调整到容器 div 中而不使其高度增加

发光效果html动画

在 React (NEXT) 中,当我try 进行动态补充时,我无法使用实例this来引用输入

是否有一种静态方式可以根据暗模式 Select 一张或另一张图像?

如何计算没有根元素的先前 html 标记(lxml python3)编辑:还获取元素