【问题标题】:Extract text content from nested HTML while excluding some specific tags; Scrapy从嵌套的 HTML 中提取文本内容,同时排除一些特定的标签;刮擦
【发布时间】:2020-03-13 04:47:54
【问题描述】:

我正在尝试从具有嵌套内容的 HTML 标记中提取文本内容。我从另一个相关问题中举了这个例子,可以看到here

>>> from parsel import Selector
>>> sel = Selector(text='''
    <p>
        Senator <a href="/people/senator_whats_their_name">What&#39s-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 标签的内容。 IE。我想得到:

Senator is furious about politics!

我怎样才能达到预期的效果?我的偏好是继续使用 Scrapy / Parsel 来获得结果,但如果不存在解决方案,我可以考虑使用任何其他第三方库。任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 您可以使用正则表达式先从文本中删除&lt;a&gt;标签,然后再进行处理。这不是最好的方法,但它会起作用。 re.sub('&lt;a(.*?)&lt;/a&gt;','',your_text)
  • 是的。这可以工作,但我有一个动态用例,我想根据复杂的选择器排除多个元素。

标签: python css xpath beautifulsoup scrapy


【解决方案1】:
  • 这是使用 beautifulsoup 的有效解决方案。
  • 你可以在 scrapy 或 parsel 中找到类似的函数并使用类似的方法。
  • 想法是将要忽略的标签内容设置为''
  • 这是一个示例。
from bs4 import BeautifulSoup as bsp

soup = bsp(''' <p>
        Senator <a href="/people/senator_whats_their_name">What&#39s-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>

【讨论】:

  • 像魅力一样工作!非常感谢详细解答!虽然我找不到任何与 Scrapy 等效的东西,但我现在会使用 bs4。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-13
  • 2021-09-12
  • 1970-01-01
  • 2019-05-11
  • 2015-02-20
  • 2017-02-22
  • 2018-12-06
相关资源
最近更新 更多