我在一个html格式的网站上搜索一个字符串("s"),它的格式是:
<td class="number">$0.48</td>我尝试使用正则表达式返回"$0.48“。它一直工作到今天,我不知道发生了什么变化,但下面是我的代码片段:
def scrubdividata(ticker):
sleep(1.0) # Time in seconds.
f = urllib2.urlopen('the url')
lines = f.readlines()
for i in range(0,len(lines)):
line = lines[i]
if "Annual Dividend:" in line:
print 'for ticker %s, annual dividend is in line'%(ticker)
s = str(lines[i+1])
print s
start = '>$'
end = '</td>'
AnnualDiv = re.search('%s(.*)%s' % (start, end), s).group(1)结果如下:
for ticker A, annual dividend is in line
<td class="number">$0.48</td>
Traceback (most recent call last):
File "test.py", line 115, in <module>
scrubdividata(ticker)
File "test.py", line 34, in scrubdividata
LastDiv = re.search('%s(.*)%s' % (start, end), s).group(1)
AttributeError: 'NoneType' object has no attribute 'group'我使用的是python 2.5 (我相信)。我听说从来没有在html中使用regex,但我需要迅速利用我有限的知识尽快完成工作,而regex是我所知道的唯一方法。现在,是我在承受后果,还是有其他问题导致了这一点?任何真知灼见都会很棒!
谢谢,B
发布于 2013-07-20 02:48:28
从文档中:
"$“匹配字符串的末尾,或者恰好在字符串末尾的换行符之前。
因此,您可能希望像这样转义该行上的美元符号:
start = '>\$'如果你正在考虑将来通过超文本标记语言进行更多的搜索,我建议你看看Beautiful Soup模块。它比正则表达式更容易理解。
https://stackoverflow.com/questions/17753245
复制相似问题