首页 > 解决方案 > 使用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 &nbsp
                <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 到文本转换器,它给了我想要的输出,但我不知道如何自己实现它。请问有什么方法/帮助吗?我真的被这个问题困住了。

这是在线转换器,如果您想查看-

https://templates.mailchimp.com/resources/html-to-text/

标签: pythonhtmlxpathweb-scrapingscrapy

解决方案


推荐阅读