python - python 中用于解析 HTML 标题标签的正则表达式模式

标签 python html regex web-scraping

我正在学习使用 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>

工作原理:

Regular expression visualization

产生:

['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/

相关文章:

JavaScript 匹配 ( 后跟一个数字

python - Twitter Trends 地方返回不同城市的相同趋势?

html - 如何根据子元素的宽度高效分配列宽?

javascript - 在 Flex 应用程序 html 页面上加载 ActiveX 对象

regex - 将旧域重定向到新域的主页

包含字符串的Python正则表达式

python - `return iterator` 和 `yield from iterator` 之间的区别

python - CSS 和 JS 无法在 Flask 框架上运行

python - 将大型数据帧插值到稀疏、不规则的索引上

jquery - 如何使用 AJAX 功能在 Magnific Popup 中加载另一个 HTML 文件?