如何从Scrapy网站获取所有纯文本?

问题描述 投票:14回答:3

在呈现HTML之后,我希望从网站上看到所有文本。我在Python中使用Scrapy框架。使用xpath('//body//text()')我能够得到它,但是使用HTML标签,我只想要文本。对此有何解决方案?

python html xpath web-scraping scrapy
3个回答
31
投票

最简单的选择是extract //body//text()join发现的一切:

''.join(sel.select("//body//text()").extract()).strip()

其中sel是一个Selector实例。

另一个选择是使用nltkclean_html()

>>> import nltk
>>> html = """
... <div class="post-text" itemprop="description">
... 
...         <p>I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework.
... With <code>xpath('//body//text()')</code> I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks !</p>
... 
...     </div>"""
>>> nltk.clean_html(html)
"I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework.\nWith xpath('//body//text()') I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks !"

另一个选择是使用BeautifulSoupget_text()

get_text()

如果您只想要文档或标记的文本部分,则可以使用get_text()方法。它返回文档中或标记下的所有文本,作为单个Unicode字符串。

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> print soup.get_text().strip()
I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework.
With xpath('//body//text()') I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks !

另一个选择是使用lxml.htmltext_content()

.text_content()

返回元素的文本内容,包括其子元素的文本内容,没有标记。

>>> import lxml.html
>>> tree = lxml.html.fromstring(html)
>>> print tree.text_content().strip()
I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework.
With xpath('//body//text()') I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks !

2
投票

你有没有尝试过?

xpath('//body//text()').re('(\w+)')

要么

 xpath('//body//text()').extract()

0
投票

xpath('//body//text()')并不总是将dipper驱动到你最后使用过的标签中的节点中(在你的case体中)。如果你输入xpath('//body/node()/text()').extract(),你会看到你html体内的节点。你可以尝试xpath('//body/descendant::text()')

© www.soinside.com 2019 - 2024. All rights reserved.