繁体   English   中英

从 html 文本中提取字符串

[英]Extracting string from html text

我得到 html 和 curl 并且只需要提取第二个表语句 请注意,卷曲的 html 是单个字符串且未格式化。 为了更好地解释,请参见以下内容:(...代表更多 html)

...
<table width="100%" cellpadding="0" cellspacing="0" class="table">
...
</table>
...
#I need to extract the following table
#from here
<table width="100%" cellpadding="4">
...
</table> #to this
...

到目前为止,我尝试了多条 SED 行,而且我认为尝试像这样匹配第二个表并不是顺利的方式:

sed -n '/<table width="100%" cellpadding="4"/,/table>/p'

html 解析器会更好,但您可以像这样使用awk

awk '/<table width="100%" cellpadding="4">/ {f=1} f; /<\/table>/ {f=0}' file
<table width="100%" cellpadding="4">
...
</table> #to this
  • /<table width="100%" cellpadding="4">/ {f=1}当找到开始时将标志f设置为 true
  • f; 如果 flage f为真,则执行默认操作,打印行。
  • /<\/table>/ {f=0}当找到 end 时,清除标志f以停止打印。

这也可以使用,但更喜欢标志控制:

awk '/<table width="100%" cellpadding="4">/,/<\/table>/' file
<table width="100%" cellpadding="4">
...
</table> #to this

将下面的脚本保存为script.py并像这样运行它:

python3 script.py input.html

此脚本解析 HTML 并检查属性( widthcellpadding )。 这种方法的优点是,如果您更改 HTML 文件的格式,它仍然可以工作,因为脚本会解析 HTML 而不是依赖精确的字符串匹配。

from html.parser import HTMLParser
import sys

def print_tag(tag, attrs, end=False):
    line = "<" 
    if end:
        line += "/"
    line += tag
    for attr, value in attrs:
        line += " " + attr + '="' + value + '"'
    print(line + ">", end="")

if len(sys.argv) < 2:
    print("ERROR: expected argument - filename")
    sys.exit(1)

with open(sys.argv[1], 'r', encoding='cp1252') as content_file:
    content = content_file.read()

do_print = False

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        global do_print
        if tag == "table":
            if ("width", "100%") in attrs and ("cellpadding", "4") in attrs:
                do_print = True
        if do_print:
            print_tag(tag, attrs)

    def handle_endtag(self, tag):
        global do_print
        if do_print:
            print_tag(tag, attrs=(), end=True)
            if tag == "table":
                do_print = False

    def handle_data(self, data):
        global do_print
        if do_print:
            print(data, end="")

parser = MyHTMLParser()
parser.feed(content)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM