为什么这段代码无法正常工作,我甚至认为它和在线教程Python Web Scraping Tutorial 5 (Network Requests)的代码一样。我试着通过在线Python解释器来运行代码。使用正则表达式的网页抓取
import urllib
import re
htmltext = urllib.urlopen("https://www.google.com/finance?q=AAPL")
regex = '<span id="ref_[^.]*_l">(.+?)</span>'
pattern = re.compile(regex)
results = re.findall(pattern,htmltext)
results
我得到:
re.pyc in findall(pattern, string, flags)
175
176 Empty matches are included in the result."""
--> 177 return _compile(pattern, flags).findall(string)
178
179 if sys.hexversion >= 0x02020000:
TypeError: expected string or buffer
预期结果(S):
112.71
帮助表示赞赏。我尝试使用“读取()”的网址,但没有奏效。根据文件,甚至应包括空的结果。谢谢
有错误在您的正则表达式模式中,正确的模式将是'(。+?)<\/span>' – ZdaR
如果您正在使用的教程建议使用正则表达式来刮取网页,找到一个不同的;存在HTML解析器是有原因的。 – jonrsharpe
@ZdaR好吧...'/'不需要在正则表达式中转义... –