我正在学习使用 re
模块和 urllib
python 中的模块并尝试编写一个简单的网络抓取工具。这是我编写的代码,用于仅抓取网站标题:
#!/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
中传递的任何其他参数标签?
最佳答案
建议您使用Beautiful Soup或任何其他用于解析 HTML 的解析器,但如果您非常想要正则表达式,则以下代码片段可以完成这项工作。
正则表达式代码:
<title.*?>(.+?)</title>
工作原理:
产生:
['Google']
['Welcome to Facebook - Log In, Sign Up or Learn More']
['reddit: the front page of the internet']
关于python - python 中用于解析 HTML 标题标签的正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20045955/