scrapy - Scrapy :仅整个页面的 RENDERED TEXT(人眼所见)
问题描述
我如何抓取相当于:在浏览器中突出显示整个页面(即不是页面源),在记事本中复制/粘贴(即没有超链接,只有文本)
class TextOnlySpider(scrapy.Spider):
name = "onepage"
allowed_domains = ["en.wikipedia.org"]
start_urls = ['https://en.wikipedia.org/wiki/Congee']
def start_requests(self):
urls = [
'https://en.wikipedia.org/wiki/Congee'
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
# Below line gives HTML/javascript, etc.
# I only want TEXT equaivalent. i.e Same text content that one gets, by copying in browser and pasting in Notepad/vim
bodyText = '\n'.join(response.xpath('//text()').extract())
yield{
'text': bodyText, #TODO only get TEXT equivalent of rendered page (text seen by human eyes)
'title': response.url, #TODO change to title
'id':response.url,
}
我想要人类阅读的文本,而不是这个答案中的页面源:
Scrapy Body Text Only
原因:
我将获取文本表示形式、页面 url 并在 elasticsearch 中对其进行索引,使其成为站点搜索解决方案。索引时我不想要凌乱的 html/js 代码。
解决方案
模块 html2text 可以在删除标签的同时将 html 转换为纯文本:
import html2text
converter = html2text.HTML2Text()
bodyText = converter.handle(response.text)
如果您还想获取呈现的文本,则需要像 Splash 这样的无头浏览器来首先呈现页面。
推荐阅读
- julia - 如何将函数标记为`@deprecate`d?
- django - 在 django rest 框架中上传临时文件
- r - 如何在 ggplot 条形图中重新排序 X 轴聚类
- javascript - 使用javascript设置文本输入字段的最小所需长度?
- python - 无法解决这个基本错误 int() 以 10 为底的无效文字
- python - 如果对反应做出反应
- html - CSS - 需要基本的聊天用户界面
- javascript - 酶仍然在 React 中找到应该通过条件渲染隐藏的元素
- linux - 如何将脏 fastq 文件排序为交错的 fastq
- c# - 在单独的线程中同步更新属性