在呈现HTML之后,我希望从网站上看到所有文本。我在Python中使用Scrapy框架。使用xpath('//body//text()')
我能够得到它,但是使用HTML标签,我只想要文本。对此有何解决方案?
最简单的选择是extract
//body//text()
和join
发现的一切:
''.join(sel.select("//body//text()").extract()).strip()
其中sel
是一个Selector
实例。
另一个选择是使用nltk
的clean_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 !"
另一个选择是使用BeautifulSoup
的get_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.html
的text_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 !
你有没有尝试过?
xpath('//body//text()').re('(\w+)')
要么
xpath('//body//text()').extract()
xpath('//body//text()')
并不总是将dipper驱动到你最后使用过的标签中的节点中(在你的case体中)。如果你输入xpath('//body/node()/text()').extract()
,你会看到你html体内的节点。你可以尝试xpath('//body/descendant::text()')
。