python - 从嵌套的 HTML 中提取文本内容,同时排除一些特定的标签;刮擦
问题描述
我正在尝试从具有嵌套内容的 HTML 标记中提取文本内容。我从可以在这里看到的另一个相关问题中获取了这个例子。
>>> from parsel import Selector
>>> sel = Selector(text='''
<p>
Senator <a href="/people/senator_whats_their_name">What's-their-name</a> is <em>furious</em> about politics!
</p>''')
>>>
>>> # Using XPath
... sel.xpath('normalize-space(//p)').extract_first()
"Senator What's-their-name is furious about politics!"
>>>
>>> # Using CSS
... "".join(sel.css("p *::text").extract())
"Senator What's-their-name is furious about politics!"
这非常接近我想要的。但是,我想排除一些特定的标签。例如,我想a
从结果字符串中排除标签的内容。即我想得到:
Senator is furious about politics!
我怎样才能达到预期的效果?我的偏好是继续使用 Scrapy / Parsel 来获得结果,但如果不存在解决方案,我可以考虑使用任何其他第三方库。任何帮助将不胜感激。谢谢!
解决方案
- 这是使用的工作解决方案
beautifulsoup
。 - 您可以在 scrapy 或 parsel 中找到类似的功能并使用类似的方法。
- 想法是将要忽略的标签的内容设置为
''
- 这是一个示例。
from bs4 import BeautifulSoup as bsp
soup = bsp(''' <p>
Senator <a href="/people/senator_whats_their_name">What's-their-name</a> is <em>furious</em> about politics!
<h1> I want to be ignored</h1>
<h2> I should not be ignored</h2>.
</p>''', 'html.parser')
for tag in soup.find_all(['a', 'h1']): # give the list of tags you want to ignore here.
tag.replace_with('')
print(soup.text)
输出:
Senator is furious about politics!
I should not be ignored.
- 上面的代码将从文本中删除
tags
您想要忽略的所有内容。 - 以下功能只会更改
string(text)
并保持标签不变。
for tag in soup.find_all(['a', 'h1']):
tag.string.replace_with('')
print(soup)
输出:
<p>
Senator <a href="/people/senator_whats_their_name"></a> is <em>furious</em> about politics!
<h1></h1>
<h2> I should not be ignored</h2>.
</p>
推荐阅读
- virtualbox - 无法通过主机获取链接到沙盒 IP 地址的 localhost
- c# - 如何更新或删除一个表中的数据并将该更改反映在另一个表中
- python - 破折号错误地格式化时间序列的 x 轴
- laravel - Composer 找不到 composer.json 文件?
- java - 我是编程新手,一直收到错误消息,不知道如何解决
- html - CSS:调整 div 大小以适应绝对定位的内容
- mysql - DB Design - 按类别显示表格
- assembly - 在 MBR 中指定分区表时,磁盘映像显示为不可引导
- google-api - 谷歌日历限制问题即使记帐已注册
- amazon-ec2 - 如何使用标记方法根据应用代码调用 ec2 实例列表