使用正则表达式在python中进行刮取不会产生任何结果?

使用正则表达式在python中进行刮取不会产生任何结果?,python,regex,Python,Regex,我正在使用Python3抓取一个网站并打印一个值。这是密码 import urllib.request import re url = "http://in.finance.yahoo.com/q?s=spy" hfile = urllib.request.urlopen(url) htext = hfile.read().decode('utf-8') regex = '<span id="yfs_l84_SPY">(.+?)</span>' code = re.

我正在使用Python3抓取一个网站并打印一个值。这是密码

import urllib.request
import re

url = "http://in.finance.yahoo.com/q?s=spy"  
hfile = urllib.request.urlopen(url)
htext = hfile.read().decode('utf-8')
regex = '<span id="yfs_l84_SPY">(.+?)</span>'
code = re.compile(regex)
price = re.findall(code,htext)
print (price)
导入urllib.request
进口稀土
url=”http://in.finance.yahoo.com/q?s=spy"  
hfile=urllib.request.urlopen(url)
htext=hfile.read().decode('utf-8')
正则表达式='(.+?)'
代码=重新编译(正则表达式)
price=re.findall(代码,htext)
印刷品(价格)
当我运行此代码段时,它会打印一个空列表,即
[]
,但我需要一个值,例如
483.33


我做错了什么?帮助

如果您没有正确使用正则表达式,有两种方法:

一,

regex='(.+?)'
代码=重新编译(正则表达式)
price=code.findall(htext)
二,

regex='(.+?)'
price=re.findall(regex,htext)

需要注意的是,Python正则表达式库在内部进行了一些缓存,因此预缓存的效果有限。

我建议您不要使用正则表达式解析HTML,因为。是的,你可以在这里用。这不是一个好习惯

我想您遇到的最大问题是,您在该页面上查找的
span
的真正
id
yfs\u l84\u spy
。注意箱子

这就是说,这里有一个在中的快速实现


请不要使用正则表达式来解析HTML。使用(
*gasp!*
)一个HTML解析器。这并不是说你不能使用它,只是有更好的预制作、内置工具已经用于解析这类东西了。检查站out@user2762289在您试图删除的网页源代码中,“spy”是小写的,而您使用大写时,您需要匹配不区分大小写或使所有内容都小写。您知道有一个Yahoo Finance API?@HamZa。你完全正确!!!将SPY更改为小写可以解决此问题。非常感谢您的支持。我尝试了两种方法,但结果仍然是一样的,一个空列表。在这种情况下,您的正则表达式根本不匹配。这几乎可以是任何东西,一个额外的空间,大写字母与小写字母,多行。。。我感谢你的建议。我将切换:)
regex = '<span id="yfs_l84_spy">(.+?)</span>'
code = re.compile(regex)
price = code.findall(htext)
regex = '<span id="yfs_l84_spy">(.+?)</span>'
price = re.findall(regex, htext)
import urllib.request
from bs4 import BeautifulSoup

url = "http://in.finance.yahoo.com/q?s=spy"  
hfile = urllib.request.urlopen(url)
htext = hfile.read().decode('utf-8')
soup = BeautifulSoup(htext)
soup.find('span',id="yfs_l84_spy")
Out[18]: <span id="yfs_l84_spy">176.12</span>
found_tag = soup.find('span',id="yfs_l84_spy") #tag is a bs4 Tag object
found_tag.next #get next (i.e. only) element of the tag
Out[36]: '176.12'