簡體   English   中英

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

[英]How to print/get specific lines in an Html file in python 3

我想從我的 HTML 文件中打印特定的行。 特定行是作為標題括起來的那一行。 我的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()

test.html 看起來像這樣

<html>
<head>
<title>
Example
</title>
</head>
<body>
<h1>Hello, world</h1>
</body>
</html>

你可以做這樣的事情:

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()返回您搜索的字符串內子字符串的起始索引,然后我們使用這些索引(在應用一些簡單的數學之后)通過使用[:]對字符串進行切片來訪問子字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM