2017-04-02 58 views
-2

我试图从html代码中提取文本。这里是我的代码:为什么使用re.findall()的正则表达式不起作用?

import re 
Luna = open('D:\Python\Luna.txt','r+') 
text=Luna.read() 
txt=re.findall('<p>\s+(.*)</p>',text) 
print txt 

然而,只有第一<p>之前消除一部分,一切都在第一<p>保持了。我应该怎样做才能改进我的代码,以便它只返回<p></p>之间的部分? 这里是原始的HTML代码的一部分:

src="/advjs/gg728x90.js"></script></td> </tr></table><div class="text" align="justify"></p><p> Sure. Eye of newt. Tongue of snake.</p><p> She added, &ldquo;Since you&rsquo;re taking Skills for Living, it&rsquo;ll be good practice.&rdquo;</p><p> For what? I wondered. Poisoning my family? &ldquo;I have to baby-sit,&rdquo; I said, a little too gleefully.</p> 
+1

关于使用正则表达式解析HTML的强制性警告:[RegEx匹配除XHTML自包含标记之外的开放标记](// stackoverflow.com/q/1732348) –

回答

1

强烈建议您使用合适的HTML解析器,像BeautifulSoup

from bs4 import BeautifulSoup 

soup = BeautifulSoup(Luna.read()) 
para_strings = (p.get_text() for p in soup.find_all('p')) 
txt = [p.strip() for p in para_strings if p.startswith(' ')] 

您可以通过使用非贪婪解决您的正则表达式操作者(?问号追加到*操作者):

txt=re.findall('<p>\s+(.*?)</p>',text) 

但是,由于HTML不是常规语言,因此很可能会遇到其他正则表达式解析问题。

相关问题