python - 使用scrapy xpath从任何HTML格式中提取文本的通用方法
问题描述
我想用 has<article>
节点从 HTML 页面中提取文本,但是在这个节点中,没有标准的节点格式。我能够提取其中的完整文本<article>
,但是我的输出与 HTML 页面上显示的不同。例如,下面是要提取的 HTML -
<article>
<div> This is first Paragraph </div>
<div> This is second Paragraph
<div> This is third paragraph  
<span> 3rd para continue </span>
</div>
</div>
</article>
这就是我的代码中的内容。
xxx = response.xpath("//article/div | //article/ul | //article/ol | //article/p")
content = ""
for eachLine in warningLetterlines:
tmp = eachLine.xpath('.//text()').extract()
content += "".join( i.replace(u'\xa0', u'') for i in tmp ) + "\n"
此代码输出为 -
This is first paragraph
This is second paragraphThis is third paragraph3rd para continue
但是,我想要的是-
This is first paragraph
This is second paragraph
This is third paragraph 3rd para continue
我试图添加一些自定义逻辑,以基于内部节点使用“\n”或“”加入列表,但正如我提到的,我的 HTML 页面不是通用格式,所以我的代码在看到新内容时就会中断. 我还想过获取节点名称列表并根据节点名称加入它(例如为/添加“\n”和为/等添加“” <div>
),但这两个列表的长度不一样。以下是我试图废弃的一些页面 - (请注意,所有 3 个页面在节点内都有不同的 html 布局。<p>
<span>
<b>
<article>
https://www.fda.gov/ICECI/EnforcementActions/WarningLetters/2017/ucm572086.htm https://www.fda.gov/ICECI/EnforcementActions/WarningLetters/2016/ucm503559.htm https://www.fda。 gov/ICECI/EnforcementActions/WarningLetters/2013/ucm376390.htm
我想以与页面上显示的完全相同的文本格式废弃这些页面。我找到了一个在线 html 到文本转换器,它给了我想要的输出,但我不知道如何自己实现它。请问有什么方法/帮助吗?我真的被这个问题困住了。
这是在线转换器,如果您想查看-
解决方案
推荐阅读
- spring - 我正在使用 Spring 开发 RESTful 应用程序。我想处理 POST 请求正文中数据类型错误的情况
- postgresql - 连接:连接超时
- java - 如何使用 Watson Discovery API 批量上传文档?
- javascript - 如果数组的一个元素在不使用迭代器的情况下不为空,则返回 false - Typescript
- c# - 在某些情况下添加行和更新行时出现并发冲突
- numerical-methods - 如何在 FiPy 中求解 Euler-Bernoulli 梁方程?
- opengl - 如何在不同的监视器上同时显示四个窗口(全屏模式,OpenGL 渲染)?
- symfony - Symfony 3.0.9 无法从我的服务访问 getUser()
- machine-learning - 序列处理文本 - 为什么填充 'pre' 是默认值?
- mongodb - 如何使用 mongodb 创建包含 Docker 的 kubernetes pod