【问题标题】:Extracting variable data from p tag从 p 标签中提取变量数据
【发布时间】:2018-04-17 16:39:34
【问题描述】:

如何使用 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>

【问题讨论】:

  • 查看BeautifulSoup,它是一个用于从 HTML 内容中提取数据的包。
  • 是的,我可以使用 beautifulsoup 获取 p 标签文本并将其存储在一个列表中,但正如我所说,这个列表是可变的,而不是 249.30,我可以有 2.4 或 2490.30。我是否需要使用正则表达式或其他东西。
  • 如果有字符串,可以根据逗号分割,用str.split(',')

标签: python python-3.x beautifulsoup


【解决方案1】:

使用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']

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 您应该使用正则表达式来解析 HTML。一旦用户有了他们需要的文本,这可能是一个可接受的解决方案。
    • 它没有尝试解析文件的 HTML 内容。 OP bever 说他想要一个解析器。是数据提取。正则表达式对此很好。
    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    相关资源
    最近更新 更多