【发布时间】:2013-11-24 14:22:20
【问题描述】:
import re
fr=open("test.html",'r')
i,j,tablestart=0,0,0
str=""
p=re.compile("<td.*?>(.*?)<\/td>")
for line in fr:
if "<table" in line:
tablestart=1
elif "</table>" in line and tablestart==1:
j,tablestart=0,0
m=p.search(line)
if m and tablestart==1:
str+='"' + m.group(1) + '"' + ","
if "</tr>" in line and tablestart==1:
print(str)
str=""
代码是从 html 表创建 csv 文件。 有没有更好或更有效的编码方式? 我不是在寻找任何 html 解析器。
【问题讨论】:
-
"我不是在寻找任何 html 解析器。" - 为什么? 那会是更好的方法。
-
我喜欢先编写我需要的东西,然后再使用其他人的代码。如果一行中有两个
我有什么建议? 您的代码假定 html 由换行符分割,这并不总是正确的,整个表格可以在一行中。我也会去解析器。请查看此问题的最高投票答案:stackoverflow.com/questions/1732348/…关于你的正则表达式。如果你的 html 包含例如会发生什么<a onClick="javascript:alert(3 > 2)">。说真的,你不能用正则表达式解析非常规语法。
标签: python regex html-table export-to-csv