如何在python 3中打印/获取HTML文件中的特定行

时间:2019-02-04 12:59:59

标签: python html python-3.x

我想从HTML文件中打印特定行。特定行是作为标题括起来的那一行。我的test.html文件发布在底部以供参考

 @if($item_offer <> '')
    @foreach($item_offer['getItemOfferDetaleData'] as $detale)
       @{{voucher_items.push({id,'1'})}}
    @endforeach
 @endif

test.html看起来像这样

import codecs
import re
f = codecs.open("test.html", 'r')
f.read()
paragraphs = re.findall(r'<html>(.*?)</html>',str(f))
print(paragraphs)
f.close()

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

import codecs
import re
g = codecs.open("test.html", 'r')
f = g.read()
start = f.find("<head>")
start = start + 7
end =  f.find("</head>")
end = end - 1
paragraphs = f[start:end]
print(paragraphs)
g.close()

此打印

<title>
Example
</title>

.find()返回所搜索字符串内子字符串的起始索引,然后(通过应用一些简单的数学运算)使用这些索引通过用[:]对该字符串进行切片来访问子字符串。