Python 为什么带有re.findall()的正则表达式不';不行?

Python 为什么带有re.findall()的正则表达式不';不行?,python,regex,findall,Python,Regex,Findall,我试图从html代码中提取文本。这是我的代码: import re Luna = open('D:\Python\Luna.txt','r+') text=Luna.read() txt=re.findall('<p>\s+(.*)</p>',text) print txt 重新导入 Luna=open('D:\Python\Luna.txt','r+')) text=Luna.read() txt=re.findall('\s+(.*)',text) 打印文本 但是

我试图从html代码中提取文本。这是我的代码:

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

',text) 打印文本
但是,它只消除了第一个
之前的部分,而保留了第一个
之后的所有内容。如何改进代码,使其只返回
之间的部分? 以下是原始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>
src=“/advjs/gg728x90.js”>当然。蝾螈之眼。蛇的舌头。

她补充道,“蛇的舌头。”;既然您;我们学习生活技能,it&rsquo;这将是一种良好的做法。”

为什么?我想知道。毒害我的家人&ldquo;“我得照看孩子,”她说;我说,有点太高兴了

我强烈建议您使用合适的HTML解析器,如:

您可以使用非贪婪运算符修复正则表达式(在
*
运算符后面附加一个
问号):

txt=re.findall('\s+(.*)

',text)

但是,由于HTML不是一种常规语言,您很可能会在使用正则表达式解析时遇到其他问题。

关于使用正则表达式解析HTML的强制性警告:
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)