Skip to main content
 首页 » 编程设计

Python Regex 找不到子字符串,但它应该

2025年05月04日23mengfanrong

我正在尝试使用 BeautifulSoup 解析 html 以尝试提取网页标题。有时由于网站写得不好,例如 Bad End 标签,这不起作用。当这不起作用时,我转到手动正则表达式

我有文字

<html xmlns="http://www.w3.org/1999/xhtml"\n      xmlns:og="http://ogp.me/ns#"\n      xmlns:fb="https://www.facebook.com/2008/fbml">\n<head>\n    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>\n    <title>\n                    .@wolfblitzercnn prepping questions for the Cheney intvw. @CNNSitRoom today. 5p. \n            </title>\n    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />... 

我正在尝试获取 <title> 之间的值和 </title>标签。它应该相当简单,但它不起作用。这是我的 python 代码。

result = re.search('\<title\>(.+?)\</title\>', html) 
if result is not None: 
    title = result.group(0) 

无论出于何种原因,这都不适用于此文本。它返回 result.group() 作为 None 或我得到一个 AttributeError。 AttributeError: 'NoneType' 对象没有属性 'groups'

我已经将此文本 C&P 到在线 python 正则表达式开发人员中并尝试了所有选项(re.match、re.findall、re.search)并且它们在那里工作但是无论出于何种原因在我的脚本中它无法在这些标签之间找到任何东西。甚至尝试其他正则表达式,例如

<title>(.*?)</title> 

等等

请您参考如下方法:

你应该使用 dotall flag使 . 也匹配换行符。

result = re.search('\<title\>(.+?)\</title\>', html, re.DOTALL) 

正如文档所说:

...without this flag, '.' will match anything except a newline