我需要解析python中的html文件,并将内容存储在列表中。 例子:['<html>', '<head>', '<meta name="robots" content="noindex">']
如何读取文件的一部分(解析),中断python中的“<”字符?
这里是我现在对buggish功能:
def getTexte(fp,compte=0): #returns the text before a html tag
txt=""
pos=fp.tell() #stock the curr position for later use
tmppos=fp.tell() #same here
for car in fp.read():
if car=="<": #if we encounter the start of a html tag
fp.seek(tmppos) #we get back to juste before the html tag
break # and we leave this damn for
txt=txt+car #we concatenate each car in the string
tmppos=fp.tell() #and stock the pos for later use
if compte==0:
fp.seek(pos)
if txt!="":
return txt
现在,这里是一个示例输出,我得到:
['<p>', 'Blablabla', 'lablabla', 'ablabla', 'blabla', 'labla', 'abla', 'bla', 'la', 'a', '</p>']
,我无法理解为什么。也许太累了。
为什么不使用像BeautifulSoup这样的解析器? – 2011-03-05 08:56:36
(1)HTML解析是一个解决的问题,甚至处理无效的,完全虚假的“标记”。 (2)你现在只是标记。解析还有很多。 (3)用手写一个词法分析器(没有正则表达式,见4)很难。手工编写完整的解析器对于大多数解析任务来说都是不切实际的。 (4)如果你打算用手工做,最好的选择是FSM,即一个正则表达式(手工编写非平凡的FSM又是非常丑陋和不需要的)。 – delnan 2011-03-05 09:00:48
也许你可以添加到你的问题最有帮助的事情是解释你真的想要解决什么问题。 (例如,不清楚为什么要将这些元素放在展开的列表中,或者想要在元素中包含文本时想要发生什么等) – 2011-03-05 09:22:27