beautifulsoup - 美丽的汤:如何在 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">```
解决方案
使用 访问标签[]
,然后将其四舍五入到小数点后两位,例如:
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
推荐阅读
- vb.net - 获取 MCC 帐户列表
- html - 在css3中制作带有蒙版和边框的六边形
- java - 使用 Spring Data JPA 的分页是否负责清除会话缓存?
- javascript - TypeError:无法使用 React-Sortable-hoc 在“onChange”事件上设置未定义的属性“名称”
- sql - 有没有办法在 BigQuery SQL 中将事件分组在 60 秒内?
- apache-spark - 出现错误 - py4j.protocol.Py4JJavaError:调用 o115.save 时出错
- javascript - 我有一个预订应用程序,我必须在日期范围选择器中禁用已预订的日期
- java - 方法类型的方法参数 (int[] nums)
- go - 有没有一种很好的方法来获取 map 中切片元素的长度,而不管其具体类型如何?
- powershell - Powershell GUI 保存文件对话框仅临时创建文件