如有以下文件html.html:
想要提取全部标签<h4></h4>内的文本,可使用如下Python代码:
import re
with open("html.html",'rU') as strf:
....str = strf.read()
res = r'(?<=<h4>).*?(?=</h4>)'
li = re.findall(res,str)
with open("new.txt","w") as wstr:
....for s in li:
........wstr.write(s)
........wstr.write("\r\n")
........print(s,'\r\n')
正则表达式r'(?<=<h4>).*?(?=</h4>)中括号部分属于向后向前查找,相当于字符串作为边界进行查找。
运行后会将标签<h4></h4>内的文本提取到文件new.txt:
-End-