从html文本中提取字符串

时间:2019-11-02 00:31:57

标签: html regex sed html-parsing extraction

我正在获取带有curl的html,只需要提取仅第二个表语句。 请注意,卷曲的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'

2 个答案:

答案 0 :(得分:2)

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;如果标志f为真,则执行默认操作,打印行。
  • /<\/table>/ {f=0}找到结尾后,清除标志f以停止打印。

这也可以使用,但是像标记控件一样好:

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

答案 1 :(得分:1)

将以下脚本另存为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)