python中用于解析HTML标题标签的正则表达式模式 [英] regex pattern in python for parsing HTML title tags

查看:15
本文介绍了python中用于解析HTML标题标签的正则表达式模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习在 python 中同时使用 re 模块和 urllib 模块并尝试编写一个简单的网络抓取工具.这是我编写的用于抓取网站标题的代码:

I am learning to use both the re module and the urllib module in python and attempting to write a simple web scraper. Here's the code I've written to scrape just the title of websites:

#!/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 - 像这样:

This gives the correct output for Google and Reddit but not for Facebook - like so:

['Google']
[]
['reddit: the front page of the internet']

这是因为,我发现在 Facebook 的页面上,title 标签如下:<title id="pageTitle">.为了适应额外的 id=,我修改了 se_regex 变量如下:these_regex="<title.+?>(.+?)</title>".但这给出了以下输出:

This is because, I found that on Facebook's page the title tag is as follows: <title id="pageTitle">. To accomodate for the additional id=, I modified the these_regex variable as follows: these_regex="<title.+?>(.+?)</title>". But this gives the following output:

[]
['Welcome to Facebook xe2x80x94 Log in, sign up or learn more']
[]

如何将两者结合起来,以便我可以考虑在 title 标签内传递的任何其他参数?

How would I combine both so that I can take into account any additional parameters passed within the title tag?

推荐答案

您正在使用正则表达式,而将 HTML 与此类表达式匹配会变得太复杂、太快.

You are using a regular expression, and matching HTML with such expressions get too complicated, too fast.

改用 HTML 解析器,Python 有几个可供选择.我建议您使用 BeautifulSoup,一个流行的 3rd 方库.

Use a HTML parser instead, Python has several to choose from. I recommend you use BeautifulSoup, a popular 3rd party library.

BeautifulSoup 示例:

BeautifulSoup example:

from bs4 import BeautifulSoup

response = urllib2.urlopen(url)
soup = BeautifulSoup(response.read(), from_encoding=response.info().getparam('charset'))
title = soup.find('title').text

由于 title 标签本身不包含其他标签,您可以在这里使用正则表达式,但是一旦您尝试解析嵌套标签,您就会 遇到极其复杂的问题.

Since a title tag itself doesn't contain other tags, you can get away with a regular expression here, but as soon as you try to parse nested tags, you will run into hugely complex issues.

您的具体问题可以通过匹配 title 标签中的附加字符来解决,可选:

Your specific problem can be solved by matching additional characters within the title tag, optionally:

r'<title[^>]*>([^<]+)</title>'

这匹配 0 个或多个 不是 结束 > 括号的字符.此处的0 或更多"可让您匹配额外的属性和普通的 </code> 标签.<em class="showen"></em></p> <p class="en">This matches 0 or more characters that are <em>not</em> the closing <code>></code> bracket. The '0 or more' here lets you match both extra attributes and the plain <code><title></code> tag.</p> <p>这篇关于python中用于解析HTML标题标签的正则表达式模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!</p> </div> <div class="arc-body-main-more"> <span onclick="unlockarc('2680128');">查看全文</span> </div> </div> <div> </div> <div class="wwads-cn wwads-horizontal" data-id="166" style="max-width:100%;border: 4px solid #666;"></div> </div> </article> <div id="arc-ad-2" class="mb-1"> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5038752844014834" crossorigin="anonymous"></script> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5038752844014834" data-ad-slot="3921941283"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> <div class="widget bgwhite radius-1 mb-1 shadow widget-rel"> <h5>相关文章</h5> <ul> <li> <a target="_blank" title="用于 HTML 解析的 Python 正则表达式 (BeautifulSoup)" href="/2353732.html"> 用于 HTML 解析的 Python 正则表达式 (BeautifulSoup); </a> </li> <li> <a target="_blank" title="用于HTML标签的正则表达式" href="/2272306.html"> 用于HTML标签的正则表达式; </a> </li> <li> <a target="_blank" title="Python使用正则表达式解析HTML" href="/2123343.html"> Python使用正则表达式解析HTML; </a> </li> <li> <a target="_blank" title="如何使用正则表达式解析HTML标签?" href="/2122316.html"> 如何使用正则表达式解析HTML标签?; </a> </li> <li> <a target="_blank" title="正则表达式解析HTML" href="/1031810.html"> 正则表达式解析HTML; </a> </li> <li> <a target="_blank" title="在bootstrap验证中用于srting模式的正则表达式" href="/1105996.html"> 在bootstrap验证中用于srting模式的正则表达式; </a> </li> <li> <a target="_blank" title="正则表达式描述正则表达式模式?" href="/1506630.html"> 正则表达式描述正则表达式模式?; </a> </li> <li> <a target="_blank" title="正则表达式拆分 HTML 标签" href="/2371908.html"> 正则表达式拆分 HTML 标签; </a> </li> <li> <a target="_blank" title="正则表达式去掉HTML标签" href="/861867.html"> 正则表达式去掉HTML标签; </a> </li> <li> <a target="_blank" title="用于解析JSON的正则表达式" href="/1683904.html"> 用于解析JSON的正则表达式; </a> </li> <li> <a target="_blank" title="用于解析JSON的正则表达式" href="/1511426.html"> 用于解析JSON的正则表达式; </a> </li> <li> <a target="_blank" title="删除HTML标签的正则表达式" href="/2633342.html"> 删除HTML标签的正则表达式; </a> </li> <li> <a target="_blank" title="html标签中的正则表达式" href="/2123347.html"> html标签中的正则表达式; </a> </li> <li> <a target="_blank" title="Python正则表达式解析流" href="/2372340.html"> Python正则表达式解析流; </a> </li> <li> <a target="_blank" title="如何用正则表达式模式替换正则表达式模式?" href="/2023853.html"> 如何用正则表达式模式替换正则表达式模式?; </a> </li> <li> <a target="_blank" title="使用正则表达式和python替换HTML标签" href="/871843.html"> 使用正则表达式和python替换HTML标签; </a> </li> <li> <a target="_blank" title="正则表达式,用于捕获重复模式" href="/1820585.html"> 正则表达式,用于捕获重复模式; </a> </li> <li> <a target="_blank" title="正则表达式,用于匹配Unicode模式" href="/2281236.html"> 正则表达式,用于匹配Unicode模式; </a> </li> <li> <a target="_blank" title="正则表达式模式" href="/1385359.html"> 正则表达式模式; </a> </li> <li> <a target="_blank" title="正则表达式模式" href="/1252732.html"> 正则表达式模式; </a> </li> <li> <a target="_blank" title="html - 正则表达式 python爬虫" href="/702298.html"> html - 正则表达式 python爬虫; </a> </li> <li> <a target="_blank" title="多个标签的Python正则表达式" href="/871303.html"> 多个标签的Python正则表达式; </a> </li> <li> <a target="_blank" title="用于查找正则表达式的正则表达式?" href="/2776335.html"> 用于查找正则表达式的正则表达式?; </a> </li> <li> <a target="_blank" title="用于密码验证的正则表达式(正则表达式)" href="/1733221.html"> 用于密码验证的正则表达式(正则表达式); </a> </li> <li> <a target="_blank" title="正则表达式引擎如何使用递归子模式解析正则表达式?" href="/1722919.html"> 正则表达式引擎如何使用递归子模式解析正则表达式?; </a> </li> </ul> </div> <div class="mb-1"> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5038752844014834" crossorigin="anonymous"></script> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-5038752844014834" data-ad-slot="3921941283"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> </div> <div class="side"> <div class="widget widget-side bgwhite mb-1 shadow"> <h5>前端开发最新文章</h5> <ul> <li> <a target="_blank" title="为什么Chrome(在Electron内部)突然重定向到chrome-error:// chromewebdata?" href="/1996151.html"> 为什么Chrome(在Electron内部)突然重定向到chrome-error:// chromewebdata?; </a> </li> <li> <a target="_blank" title="错误102(net :: ERR_CONNECTION_REFUSED):服务器拒绝连接" href="/749568.html"> 错误102(net :: ERR_CONNECTION_REFUSED):服务器拒绝连接; </a> </li> <li> <a target="_blank" title="如何解决'重定向已被CORS策略阻止:没有'Access-Control-Allow-Origin'标题'?" href="/1009885.html"> 如何解决'重定向已被CORS策略阻止:没有'Access-Control-Allow-Origin'标题'?; </a> </li> <li> <a target="_blank" title="如何处理“Uncaught(in promise)DOMException:play()失败,因为用户没有首先与文档交互。”在桌面上使用Chrome 66?" href="/884909.html"> 如何处理“Uncaught(in promise)DOMException:play()失败,因为用户没有首先与文档交互。”在桌面上使用Chrome 66?; </a> </li> <li> <a target="_blank" title="警告:添加非被动事件侦听器到滚动阻塞'touchstart'事件" href="/818517.html"> 警告:添加非被动事件侦听器到滚动阻塞'touchstart'事件; </a> </li> <li> <a target="_blank" title="如何在浏览器中播放.TS文件(视频/ MP2T媒体类型)?" href="/343346.html"> 如何在浏览器中播放.TS文件(视频/ MP2T媒体类型)?; </a> </li> <li> <a target="_blank" title="此请求已被阻止;内容必须通过HTTPS提供" href="/886417.html"> 此请求已被阻止;内容必须通过HTTPS提供; </a> </li> <li> <a target="_blank" title="资源解释为样式表,但转换为MIME类型text / html(似乎与web服务器无关)" href="/562873.html"> 资源解释为样式表,但转换为MIME类型text / html(似乎与web服务器无关); </a> </li> <li> <a target="_blank" title="通过HTTPS加载页面但请求不安全的XMLHttpRequest端点" href="/885901.html"> 通过HTTPS加载页面但请求不安全的XMLHttpRequest端点; </a> </li> <li> <a target="_blank" title="拒绝从执行脚本'*',因为它的MIME类型(“应用/ JSON')不是可执行文件,并严格MIME类型检查被启用。" href="/47347.html"> 拒绝从执行脚本'*',因为它的MIME类型(“应用/ JSON')不是可执行文件,并严格MIME类型检查被启用。; </a> </li> </ul> </div> <div class="widget widget-side bgwhite mb-1 shadow"> <h5> 热门教程 </h5> <ul> <li> <a target="_blank" title="Java教程" href="/OnLineTutorial/java/index.html"> Java教程 </a> </li> <li> <a target="_blank" title="Apache ANT 教程" href="/OnLineTutorial/ant/index.html"> Apache ANT 教程 </a> </li> <li> <a target="_blank" title="Kali Linux教程" href="/OnLineTutorial/kali_linux/index.html"> Kali Linux教程 </a> </li> <li> <a target="_blank" title="JavaScript教程" href="/OnLineTutorial/javascript/index.html"> JavaScript教程 </a> </li> <li> <a target="_blank" title="JavaFx教程" href="/OnLineTutorial/javafx/index.html"> JavaFx教程 </a> </li> <li> <a target="_blank" title="MFC 教程" href="/OnLineTutorial/mfc/index.html"> MFC 教程 </a> </li> <li> <a target="_blank" title="Apache HTTP客户端教程" href="/OnLineTutorial/apache_httpclient/index.html"> Apache HTTP客户端教程 </a> </li> <li> <a target="_blank" title="Microsoft Visio 教程" href="/OnLineTutorial/microsoft_visio/index.html"> Microsoft Visio 教程 </a> </li> </ul> </div> <div class="widget widget-side bgwhite mb-1 shadow"> <h5> 热门工具 </h5> <ul> <li> <a target="_blank" title="Java 在线工具" href="/Onlinetools/details/4"> Java 在线工具 </a> </li> <li> <a target="_blank" title="C(GCC) 在线工具" href="/Onlinetools/details/6"> C(GCC) 在线工具 </a> </li> <li> <a target="_blank" title="PHP 在线工具" href="/Onlinetools/details/8"> PHP 在线工具 </a> </li> <li> <a target="_blank" title="C# 在线工具" href="/Onlinetools/details/1"> C# 在线工具 </a> </li> <li> <a target="_blank" title="Python 在线工具" href="/Onlinetools/details/5"> Python 在线工具 </a> </li> <li> <a target="_blank" title="MySQL 在线工具" href="/Onlinetools/Dbdetails/33"> MySQL 在线工具 </a> </li> <li> <a target="_blank" title="VB.NET 在线工具" href="/Onlinetools/details/2"> VB.NET 在线工具 </a> </li> <li> <a target="_blank" title="Lua 在线工具" href="/Onlinetools/details/14"> Lua 在线工具 </a> </li> <li> <a target="_blank" title="Oracle 在线工具" href="/Onlinetools/Dbdetails/35"> Oracle 在线工具 </a> </li> <li> <a target="_blank" title="C++(GCC) 在线工具" href="/Onlinetools/details/7"> C++(GCC) 在线工具 </a> </li> <li> <a target="_blank" title="Go 在线工具" href="/Onlinetools/details/20"> Go 在线工具 </a> </li> <li> <a target="_blank" title="Fortran 在线工具" href="/Onlinetools/details/45"> Fortran 在线工具 </a> </li> </ul> </div> </div> </div> <script type="text/javascript">var eskeys = 'python,中,用于,解析,html,标题,标签,的,正则表达式,模式'; var cat = 'cc';';//qianduan</script> </div> <div id="pop" onclick="pophide();"> <div id="pop_body" onclick="event.stopPropagation();"> <h6 class="flex flex101"> 登录 <span onclick="pophide();">关闭</span> </h6> <div class="pd-1"> <div class="wxtip center"> <span>扫码关注<em>1秒</em>登录</span> </div> <div class="center"> <img id="qr" src="https://huajiakeji.com/Content/Images/qrydx.jpg" alt="" style="width:150px;height:150px;" /> </div> <div style="margin-top:10px;display:flex;justify-content: center;"> <input type="text" placeholder="输入验证码" id="txtcode" autocomplete="off" /> <input id="btngo" type="button" onclick="chk()" value="GO" /> </div> <div class="center" style="margin: 4px; font-size: .8rem; color: #f60;"> 发送“验证码”获取 <em style="padding: 0 .5rem;">|</em> <span style="color: #01a05c;">15天全站免登陆</span> </div> <div id="chkinfo" class="tip"></div> </div> </div> </div> <script type="text/javascript" src="https://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script> <script type="text/javascript" src="https://img01.yuandaxia.cn/Scripts/highlight.min.js"></script> <script type="text/javascript" src="https://img01.yuandaxia.cn/Scripts/base.js?v=0.22"></script> <script type="text/javascript" src="https://img01.yuandaxia.cn/Scripts/tui.js?v=0.11"></script> <footer class="footer"> <div class="container"> <div class="flink mb-1"> 友情链接: <a href="https://www.it1352.com/" target="_blank">IT屋</a> <a href="https://huajiakeji.com/" target="_blank">Chrome插件</a> <a href="https://www.cnplugins.com/" target="_blank">谷歌浏览器插件</a> </div> <section class="copyright-section"> <a href="https://www.it1352.com" title="IT屋-程序员软件开发技术分享社区">IT屋</a> ©2016-2022 <a href="http://www.beian.miit.gov.cn/" target="_blank">琼ICP备2021000895号-1</a> <a href="/sitemap.html" target="_blank" title="站点地图">站点地图</a> <a href="/Home/Tags" target="_blank" title="站点标签">站点标签</a> <a target="_blank" alt="sitemap" href="/sitemap.xml">SiteMap</a> <a href="/1155981.html" title="IT屋-免责申明"><免责申明></a> 本站内容来源互联网,如果侵犯您的权益请联系我们删除. </section> <!--统计代码--> <script type="text/javascript"> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "https://hm.baidu.com/hm.js?0c3a090f7b3c4ad458ac1296cb5cc779"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> <script type="text/javascript"> (function () { var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })(); </script> </div> </footer> </body> </html>