【问题标题】:make python variable triple quotation style制作python变量三引号样式
【发布时间】:2013-08-16 10:06:45
【问题描述】:

我正在尝试解析类名如 class="link" 的 html,我的问题是想要读取变量中的每一行然后解析它,但它应该与三引号一起使用,我怎样才能创建一个字符串三引号样式的变量。谢谢。

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()

var = open('./index.html','r')
strings = var.read()



parser.feed('<html><head><title>Test</title></head>'
        '<body><h1>Parse me!</h1></body></html>')

好吧,如果我从本地文件中读取内容,我该如何解析字符串 var?

index.html:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
</head>
<body>
    <div class="row">
        <h1>hello world</h1>
            <div class="row">
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id, excepturi, consequatur sed nobis facere veritatis tempore qui ipsum enim dignissimos!</p>
            </div>
    </div>
</body>
</html>

如果我将这个 html 作为一个大字符串读取,我该如何解析它,我只想获取 h1 标签中的内容。感谢您的宝贵时间。

【问题讨论】:

  • 您能否发布一个示例并解释您到目前为止所做的尝试?
  • 三引号样式是什么意思?您是否只想在输入中包含换行符和引号字符?
  • 您的代码看起来不错,它可以运行(省略文件读取部分,因为我没有您的index.html 文件)。问题是什么?你能提供一个你描述的有问题的输入的例子吗?
  • Opps,我不尝试,它对我有用。再次感谢您的光临。

标签: python html css parsing


【解决方案1】:
   h1 = false

   class MyHTMLParser(HTMLParser):
       def handle_starttag(self, tag, attrs):
          ## print "Encountered a start tag:", tag
          if tag == 'h1':
                 h1 = true
       def handle_endtag(self, tag):
          ## print "Encountered an end tag :", tag
          if tag == 'h1':
                 h1 = false
       def handle_data(self, data):
           ## print "Encountered some data  :", data
           if h1:
                 print data

【讨论】:

  • 这就是我想要的。感谢您的宝贵时间。
猜你喜欢
  • 2018-09-29
  • 1970-01-01
  • 2016-08-07
  • 2021-10-12
  • 2018-12-08
  • 1970-01-01
  • 2011-04-22
  • 2012-04-11
  • 1970-01-01
相关资源
最近更新 更多