【问题标题】:How to retrieve the value using a regular expression in Python?如何在 Python 中使用正则表达式检索值?
【发布时间】:2012-08-25 05:22:48
【问题描述】:

我写了这样的代码:

print re.findall(r'(<td width="[0-9]+[%]?" align="(.+)">|<td align="(.+)"> width="[0-9]+[%]?")([ \n\t\r]*)([0-9,]+\.[0-9]+)([ \n\t\r]*)([&]?[a-zA-Z]+[;]?)([ \n\t\r]*)<span class="(.+)">',r.text,re.MULTILINE)

得到这条线:

<td width="47%" align="left">556.348&nbsp;<span class="uccResCde">

我想要值 556.348。如何使用regular expressions 获得它?

【问题讨论】:

    标签: python html regex python-3.x python-2.7


    【解决方案1】:

    the HTMLParser documentation 直接剪切和粘贴会从标签中获取数据,但不使用正则表达式。

    from HTMLParser import HTMLParser
    
    # Create a subclass and override the handler methods
    class MyHTMLParser(HTMLParser):
        def handle_starttag(self, tag, attrs):
            print "Encountered a start tag:", tag
        def handle_endtag(self, tag):
            print "Encountered an end tag :", tag
        def handle_data(self, data):
            print "Encountered some data  :", data
    
    # Instantiate the parser and fed it some HTML
    parser = MyHTMLParser()
    parser.feed('<td width="47%" align="left">556.348&nbsp;<span class="uccResCde">')
    

    【讨论】:

      【解决方案2】:

      这是一个解释如何获取匹配组的解决方案。你应该阅读the documentation

      import re
      
      text_to_parse= '<td width="47%" align="left">556.348&nbsp;<span class="uccResCde">'
      pattern = r'(<td width="[0-9]+[%]?" align="(.+)">|<td align="(.+)"> width="[0-9]+[%]?")([ \n\t\r]*)([0-9,]+\.[0-9]+)([ \n\t\r]*)([&]?[a-zA-Z]+[;]?)([ \n\t\r]*)<span class="(.+)">'
      m = re.search(pattern, text_to_parse)
      m.group(5)
      

      但是为了解析 HTML,不需要使用正则表达式。而是使用 HTML 解析器,例如 Beautiful Soup:

      from bs4 import BeautifulSoup
      
      soup = BeautifulSoup(text_to_parse)
      soup.text
      

      【讨论】:

      • 值可能会不断变化。我想从那里获取值。
      • 我没有拒绝你。问题是我也不能用漂亮的汤。我应该只使用正则表达式
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      • 2016-09-01
      • 1970-01-01
      • 2012-12-16
      相关资源
      最近更新 更多