首页 > 解决方案 > 美丽的汤:如何在 td 中获取时间戳

问题描述

如何从“数据时间戳”中获取值并使用 BeautifulSoup 将其转换为整数。我正在遍历网站上的每一行(这是一个 tr 类)。

所以如果我将代码设置为

ratings = []
rows = soup.select('tbody tr')
for row in rows:
'insert code here'
ratings.append(rating)

但是,我似乎无法访问数据时间戳中的值。我试过使用 attrs 但我假设我做错了。任何帮助将非常感激。

<td data-timestamp="4.5833333333333" class="hide-on-hover fill-space relative">
              <div class="col border-box text-center nowrap row large-up-text-right padding-horz-small push">```
                 

标签: beautifulsoup

解决方案


使用 访问标签[],然后将其四舍五入到小数点后两位,例如:

from bs4 import BeautifulSoup

html_doc = """<td data-timestamp="4.5833333333333" class="hide-on-hover fill-space relative">
              <div class="col border-box text-center nowrap row large-up-text-right padding-horz-small push">```"""

soup = BeautifulSoup(html_doc, 'html.parser')

ratings = []
rows = soup.select('td')
for row in rows:
   ratings.append(round(float(soup.select_one('td')['data-timestamp']), 2))

print(*ratings)

输出:

4.58

推荐阅读