【问题标题】:Python regex match to parse html [duplicate]Python正则表达式匹配解析html [重复]
【发布时间】:2013-12-05 09:44:23
【问题描述】:

我正在玩python,我想用正则表达式解决以下问题:

我想用正则表达式从网站解析 html。 我以字符串形式获取该站点。我把网站的每一行都放在一个循环中。

for line in html.splitlines():
    #print line
    matchObj = re.match( r'<h1(.*)>', line, re.M|re.I)
    if matchObj:
        print matchObj.group()

我想匹配与
&lt;h1 class="hidden offscreen" tabindex="0"&gt; anyContent &lt;/h1&gt;匹配的每一行

【问题讨论】:

  • 您需要什么好的提示?什么对你有用/没用?你看过 re 模块的文档了吗?
  • 使用 HTMLParser 模块。如果你看看他们的例子,这并不难。
  • 为什么每个人都想用正则表达式解析 html?
  • @InbarRose Obligatory link:选择答案而不是非答案。

标签: python regex parsing


【解决方案1】:

一个天真的版本是

html = '<h1 class="hidden offscreen" tabindex="0"> anyContent </h1>'
print re.search('(?is)<h1[^>]*>(.+?)</h1>', html).group(1)

请注意,这假定 html 是有效的,如果不是这样,使用解析器会更安全:

from BeautifulSoup import BeautifulSoup
print BeautifulSoup(html).find("h1").text

【讨论】:

    【解决方案2】:

    如果您只想解析此类内容,您可以使用正则表达式来执行以下操作:

    <h1 class="hidden offscreen" tabindex="0">(?p<content>.*?)</h1>
    

    请勿尝试将此扩展到其他标签或案例。 HTML 使用的语法比正则表达式更复杂。

    我同意 Hai Vu 的评论,使用 HTMLParser 模块。还是美汤:http://www.crummy.com/software/BeautifulSoup/

    【讨论】:

      【解决方案3】:

      这是我写回的旧脚本。它应该让你开始。注意handle_starttag()方法中的attrs

      import HTMLParser
      
      class HeadersParser(HTMLParser.HTMLParser, object):
          def __init__(self):
              super(HeadersParser, self).__init__()
              self.in_header = False
          def handle_starttag(self, tag, attrs):
              if tag.lower() == 'h1':
                  self.in_header = True
          def handle_endtag(self, attrs):
              self.in_header = False
          def handle_data(self, data):
              if self.in_header:
                  print '{}'.format(data)
                  
      with open('sample.html') as f:
          html_contents = f.read()
          
      parser = HeadersParser()
      parser.feed(html_contents)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-23
        • 2012-09-12
        • 1970-01-01
        • 1970-01-01
        • 2018-04-29
        • 2016-06-15
        相关资源
        最近更新 更多