【发布时间】:2017-02-02 03:33:08
【问题描述】:
我不知道为什么这段代码不起作用,甚至认为它与在线教程 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
预期结果:
112.71
帮助表示赞赏。我尝试在 url 上使用“read()”,但这没有用。根据文档,甚至应该包括空结果。谢谢
【问题讨论】:
-
你的正则表达式有错误,正确的模式是
<span id="ref_[^.]*_l">(.+?)<\/span> -
如果您使用的教程建议使用正则表达式来抓取网页,请另找一个; HTML 解析器的存在是有原因的。
-
@ZdaR 好吧不...
/不需要在正则表达式中转义... -
应避免使用任何告诉您使用正则表达式解析 html 的教程。 Beautifulsoup 可以在一行中可靠地做到这一点
BeautifulSoup(htmltext).select("span[id^=ref_]")
标签: python regex web-scraping typeerror