另一个变量中的精确正则表达式不返回结果

时间:2015-08-31 19:38:36

标签: python regex

#http://finance.yahoo.com/q?s=spy

import urllib.request
import re


htmlfile = urllib.request.urlopen("http://finance.yahoo.com/q?s=spy")
htmltext = htmlfile.read().decode("utf-8")

regex = re.compile('<span id="yfs_184_spy">(.+?)</span>')
regex1 = re.compile('<span id="yfs_l84_spy">(.+?)</span>')
regex2 = re.compile('<span id="yfs_184_spy">(.+?)</span>')

price = re.findall(regex, htmltext)
price2 = re.findall(regex1, htmltext)
price3 = re.findall(regex2, htmltext)
price4 = re.findall(regex, htmltext)

print(price)
print(price2)
print(price3)
print(price4)

上面的代码返回此结果:

[]
['197.55']
[]
[]

我不知道为什么其他正则表达式变量不返回任何匹配对象(price,price3,price 4)。 Price2变量html正则表达式模式从URL的源复制并粘贴到工作的编辑器中。当我因某种原因键入HTML时,它不会返回匹配对象。 非常感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

你的正则表达式中只有一次找到字符串的原因是因为这是唯一匹配的字符串。在第一个和第三个中,字符串是“yfs_184_spy” - 中心3个字符是“一个八个四”。在第二个中,字符串是“yfs_l84_spy” - 即“el eight four”。 code字体掩盖了问题中的字体。得到你的字符串,你会得到更好的结果。