Python:找不到文本

2024-10-01 11:36:57 发布

您现在位置:Python中文网/ 问答频道 /正文

此正则表达式:

<span style=\"color: #008000;\" data-iceapw=\"1\">HIGH<\/span> 

尝试查找以下文本:

<span style="color: #008000;" data-iceapw="1">HIGH<\span> 

在类似这样的代码片段中,例如:

<p data-iceapw="9" data-iceapc="4">Factual Reporting: <strong data-iceapw="1" data-iceapc="1"><span style="color: #008000;" data-iceapw="1">HIGH</span><br />
</strong>World Press Freedom Rank: <span style="color: #ff9900;" data-iceapw="2" data-iceapc="1"><strong data-iceapw="2">USA 45/180</strong></span></p>

如果我们使用这个网站来测试它,我们可以检查它是否正确:https://regex101.com/

但是,当我尝试对Python执行同样的操作时,Python没有检测到以下文本:

<span style="color: #008000;" data-iceapw="1">HIGH<\span>

我尝试检测该文本的python代码是:

re.search('<span style=\"color: #008000;\" data-iceapw=\"1\">HIGH<\/span>', str(soup), re.IGNORECASE)

我做错了什么

编辑I:

我不明白为什么这个正则表达式工作得很好:

 re.search('<strong><span style=\"color: #008000;\">HIGH<br>\n<\/span><\/strong>', str(soup), re.IGNORECASE)

帮我找到我要找的代码。但是,另一个正则表达式不起作用:

re.search('<span style=\"color: #008000;\" data-iceapw=\"1\">HIGH<\/span>', str(soup))

当我试图找到这个:

<span style="color: #008000;" data-iceapw="1">HIGH</span>

在此代码中:

<p data-iceapw="9" data-iceapc="4">Factual Reporting: <strong data-iceapw="1" data-iceapc="1"><span style="color: #008000;" data-iceapw="1">HIGH</span><br />
</strong>World Press Freedom Rank: <span style="color: #ff9900;" data-iceapw="2" data-iceapc="1"><strong data-iceapw="2">USA 45/180</strong></span></p>

Tags: 代码文本brresearchdatastylecolor
1条回答
网友
1楼 · 发布于 2024-10-01 11:36:57

您已经有了一个soup对象,为什么不使用它来搜索呢

from bs4 import BeautifulSoup

data = '''\
<div>
<span>not this</span>
<span style="color: #008000;" data-iceapw="1">HIGH</span>
<span>nor this</span>
</div>
'''

soup = BeautifulSoup(data, "html.parser")

matches = soup.select("span[data-iceapw='1']")
for span in matches:
    print(span)

相关问题 更多 >