好吧,所以我正在使用正则表达式来搜索站点中的所有标题信息.
我编译了正则表达式:
regex = re.compile(r'''
<h[0-9]>\s?
(<a[ ]href="[A-Za-z0-9.]*">)?\s?
[A-Za-z0-9.,:'"=/?;\s]*\s?
[A-Za-z0-9.,:'"=/?;\s]?
''', re.X)
Run Code Online (Sandbox Code Playgroud)
当我在python reg ex中运行它时.测试员,它非常好用.
样本数据:
<body>
<h1>Dog </h1>
<h2>Cat </h2>
<h3>Fancy </h3>
<h1>Tall cup of lemons</h1>
<h1><a href="dog.com">Dog thing</a></h1>
</body>
Run Code Online (Sandbox Code Playgroud)
现在,在REDemo中,它运行得非常好.
但是,当我把它放在我的python代码中时,它只会打印出来 <a href="dog.com">
这是我的python代码,我不确定我是做错了什么还是翻译时丢失了什么.我感谢您的帮助.
stories=[]
response = urllib2.urlopen('http://apricotclub.org/duh.html')
html = response.read().lower()
p = re.compile('<h[0-9]>\\s?(<a href=\"[A-Za-z0-9.]*\">)?\\s?[A-Za-z0-9.,:\'\"=/?;\\s]*\\s?[A-Za-z0-9.,:\'\"=/?;\\s]?')
stories=re.findall(p, html)
for i in stories:
if len(i) >= 5:
print i
Run Code Online (Sandbox Code Playgroud)
我还应该注意,当我(<a href=\"[A-Za-z0-9.]*\">)?从正则表达式中取出它时,它适用于非链接<hN>行.
Jer*_*rub 23
在过去的几天里,这个问题已经以多种形式提出,所以我将非常清楚地说出这个问题.
使用BeautifulSoup,html5lib或lxml.html.请.