【发布时间】:2013-12-01 11:52:58
【问题描述】:
我正在学习在 python 中同时使用re 模块和urllib 模块,并尝试编写一个简单的网络爬虫。这是我编写的仅用于抓取网站标题的代码:
#!/usr/bin/python
import urllib
import re
urls=["http://google.com","https://facebook.com","http://reddit.com"]
i=0
these_regex="<title>(.+?)</title>"
pattern=re.compile(these_regex)
while(i<len(urls)):
htmlfile=urllib.urlopen(urls[i])
htmltext=htmlfile.read()
titles=re.findall(pattern,htmltext)
print titles
i+=1
这为 Google 和 Reddit 提供了正确的输出,但为 Facebook 提供了正确的输出 - 就像这样:
['Google']
[]
['reddit: the front page of the internet']
这是因为,我发现在 Facebook 的页面上,title 标签如下:<title id="pageTitle">。为了适应额外的id=,我将these_regex 变量修改如下:these_regex="<title.+?>(.+?)</title>"。但这给出了以下输出:
[]
['Welcome to Facebook \xe2\x80\x94 Log in, sign up or learn more']
[]
如何将两者结合起来,以便考虑在title 标记中传递的任何其他参数?
【问题讨论】:
-
你真的想使用合适的 HTML 解析器;我建议你改用 BeautifulSoup。
标签: python html regex web-scraping