我刚刚开始学习Python中的正则表达式,并且我已经在我想要完成的工作上取得了一些进展。
import urllib.request
import urllib.parse
import re
x = urllib.request.urlopen("http://www.SOMEWEBSITE.com")
contents = x.read()
paragraphs = re.findall(r'<p>(.*?)</p>', str(contents))
因此,使用该正则表达式,我能够找到段落标题之间的所有内容,但如果我想查找包含特定单词的段落,该怎么办?例如,解析所有包含单词&#34; cat&#34;在他们中。我知道(。*?)可以找到所有内容,但我对于找到具有特定关键字的段落的直觉感到有点迷失。
无论如何,谢谢。
答案 0 :(得分:4)
最好使用BeautifulSoup。例如:
import urllib2
html = urllib2.urlopen("http://www.SOMEWEBSITE.com").read()
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
# now you can search the soup
<强>文档强>
但是......如果必须使用正则表达式:
>>> str = "<p>This is some cat in a paragraph.</p>"
>>> re.findall(r'<p>(.*cat.*)</p>', str)
['This is some cat in a paragraph.']