html - 从 html 中清理数据
问题描述
我正在尝试清理通过网络抓取提取的一部分数据。包含数据的 HTML 代码如下:
<li class="price-was">
$1,699.00
<span class="price-was-data" style="display: none">1699.00</span>
</li>
要提取数据,我使用以下代码行:
price_products_before = product.findAll("li",{"class":"price-was"})
PriceBefore = price_products_before[0].text
我使用它是因为数据如下:
'\r\n $1,699.00\r\n 1699.00\n'
使用以下代码行,我设法以某种方式对其进行了清理,但我仍然有两倍的数字。
PriceBefore = price_products_before[0].text.strip().replace("\r\n","")
我只需要一次 1699 没有任何空格 \r 或 \n。
解决方案
from bs4 import BeautifulSoup
html = """<li class="price-was">
$1,699.00
<span class="price-was-data" style="display: none">1699.00</span>
</li>"""
soup = BeautifulSoup(html, 'html.parser')
try:
print(soup.find("li", class_="price-was").next_element.strip())
except:
print("Not Found")
输出:
$1,699.00
推荐阅读
- python - Pandas 应用:自动拆柱的函数原型
- github - 即使对于公共存储库,github 是否也需要 SSH 身份验证?
- android - 连接到 Google Fit - 新的 OAuth 同意屏幕错误
- encryption - MsCrypto 导入密钥方法在 IE11 中失败,出现“无效争论”错误
- julia - 需要帮助理解 Julia 的注意力机制 Transformers.jl 包中的 nntopo 宏
- java - 使用 Gradle 编译 C JNI
- c# - 为什么自定义窗口中的 PartialView 模型没有传递给控制器进行保存?但它可以正确呈现以供查看
- git - 如何重新定位 git repo 的整个主分支
- python - 处理 CSV 文件时的 Pandas 数据帧 KeyError
- python - 尽管在 Python Tutor 中工作,但 Collatz Sequence 没有任何反应