0
我的任務是查找標籤之間的所有文本。在python中查找文件中的標籤,而不使用美化功能
這裏是我的代碼:
import urllib.request
import urllib.parse
import re
file = open("file.txt", "r")
s = file.read()
file.close()
file.encode('utf-8')
files = re.findall(r'<a href="(.*?)">(.*?)</a>', str(file))
if files:
for link, title in files:
print (title)
我的txt文件包含HTML這是不完全的HTML有效。然而,html的有效性並不重要。我無法更改文件。
輸出一直工作,直到它遇到一個span元素,然後它只輸出一個原始字符串。
你用什麼with'bs'解析器?默認的解析器不能很好地處理部分有效的HTML。試試'BeautifulSoup(「file.txt」,「html5lib」)'。用正則表達式解析HTML是一個壞主意。 – DyZ
@DYZ我不能使用美麗的湯作爲任務說我不允許使用它。 –
告訴你的老師他錯了:http://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not。而你的'str(file)'必須真的是's'。 – DyZ