从p标签中提取变量数据

2024-05-19 01:38:12 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用python从下面的代码中提取249.30 251.50 252.55 246.80 248.20(假设位数是可变的,即代替249.30,我可以说是2.4或2490.30)

    <html>
    <body>
    <p>
     BSE##B#As on 17 Apr 18 | 16:00@C#7@P#@HL#249.30,251.50,252.55,246.80,248.20,Listed
    </p>
    </body>
   </html>

Tags: 代码onhtmlasbodyhlaprbse
2条回答

下面的正则表达式应该与这些数字匹配:(\d+[\.])?\d+

import re

regex = re.compile('(\d+[\.])?\d+')
print(regex.match(content))

使用BeautifulSoup

演示:

s = """<html>
    <body>
    <p>
     BSE##B#As on 17 Apr 18 | 16:00@C#7@P#@HL#249.30,251.50,252.55,246.80,248.20,Listed
    </p>
    </body>
   </html>"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(s, "html.parser")
print(soup.find("p").text)
print(re.findall("\d+\.\d+" ,soup.find("p").text))     

输出:

BSE##B#As on 17 Apr 18 | `16:00@C#7@P#@HL#249.30,251.50,252.55,246.80,248.20,Listed`
[u'249.30', u'251.50', u'252.55', u'246.80', u'248.20']

相关问题 更多 >

    热门问题