python - BeautifulSoup 如何删除文本具有特定值的标签
问题描述
我正在尝试从 wikipedia 上抓取一些文章,并发现有一些我希望排除的条目。
在下面的情况下,我想排除a
内容等于Archived
or的两个标签Wayback Machine
。没有必要将文本作为因素。我看到 href 值也可用作 url 上的排除项archive.org
或/wiki/Wayback_Machine
<li id="cite_note-22">
<span class="mw-cite-backlink">
<b>
<a href="#cite_ref-22" aria-label="Jump up" title="Jump up">^</a>
</b>
</span>
<span class="reference-text">
<a rel="nofollow" class="external text" href="https://www.somelink.com">Article Text I want to keep</a>
<a rel="nofollow" class="external text" href="https://www.someotherlink.com">Archived</a>
<a href="/wiki/Wayback_Machine" title="Wayback Machine">Wayback Machine</a>
</span>
</li>
我尝试如下使用分解。但是发现这会返回错误'str' object has no attribute 'descendants'
removeWayback = BeautifulSoup.find_all('a', {'title':'Wayback Machine'})
removeArchive = BeautifulSoup.find(text="Archive")
removeWayback.decompose()
removeArchive.decompose()
removeWayback = BeautifulSoup.find_all('a', {'title':'Wayback Machine'})
File "/usr/local/lib/python3.8/site-packages/bs4/element.py", line 1780, in find_all generator = self.descendants
AttributeError: 'str' object has no attribute 'descendants'
我也尝试过使用exclude
,但我有类似的问题。
有没有更好的方法来忽略这些链接?
解决方案
你可以试试这个:
import re
from bs4 import BeautifulSoup
html = """<li id="cite_note-22">
<span class="mw-cite-backlink">
<b>
<a href="#cite_ref-22" aria-label="Jump up" title="Jump up">^</a>
</b>
</span>
<span class="reference-text">
<a rel="nofollow" class="external text" href="https://www.somelink.com">Article Text I want to keep</a>
<a rel="nofollow" class="external text" href="https://www.someotherlink.com">Archived</a>
<a href="/wiki/Wayback_Machine" title="Wayback Machine">Wayback Machine</a>
</span>
</li>"""
soup = BeautifulSoup(html, "html.parser")
for anchor in soup.find_all(lambda t: t.name == 'a' and not re.search(r'Wayback|Archived|\^', t.text)):
print(f"{anchor.text} - {anchor.get('href')}")
输出:
Article Text I want to keep - https://www.somelink.com
编辑回答评论:
您可以通过使用ofclass
并将正则表达式条件放入循环中进行匹配。text
attrs=
.find_all()
soup = BeautifulSoup(html, "html.parser")
for anchor in soup.find_all("a", attrs={"class": "external text"}):
if not re.search(r'Wayback|Archived', anchor.text):
print(f"{anchor.text} - {anchor.get('href')}")
输出:
Article Text I want to keep - https://www.somelink.com
推荐阅读
- javascript - 通过 Ajax 进行基本身份验证,无需在对话框中输入用户名和密码即可访问受 https 保护的页面
- javascript - 如果所有子元素都被隐藏,则搜索隐藏父元素
- ios - iOS 应用程序中的按钮在 VM 上表现异常
- angular - 如何在经过消毒的输入上书写?
- android - 如何删除相机焦点上的锚节点
- ms-access - 打开表单并将未绑定的 ComboBox 设置为特定值
- javascript - 将颜色更改应用于图像作为叠加层,保持原始纹理/着色器 Javascript
- python - SESSION_COOKIE_SECURE=Django 2.2 中的 True 将管理员登录重定向到自身
- sql - 两个具有相同内容的表会破坏数据规范化吗?
- java - 查找最小长度为 2 个字符的所有常见子字符串