【问题标题】:Python Html: Extract Parts of Text from html filePython Html:从 html 文件中提取部分文本
【发布时间】:2019-04-10 10:53:07
【问题描述】:

我目前正在做一个项目,我下载了一堆相关的 html 文件并从中收集数据。我注意到的一件事是,尽管 html 文件的整体格式相似,但有时不同的文件使用不同的标签来存储相似的信息。

例如,在一个文件中可能是:

<html>
<head>
<p> Title: The GodFather </p>
<p> Author: Mario Puzo </p>
</head>
<html>

在另一个例子中,它可能是:

<html>
<head>
<p> Heading </p>
<pre> Ebook from xyz site: Please donate to our foundation at www.abc.com
Title: The GodFather
Author: Mario Puzo
</pre>
</head>
</html>

我可以肯定地说,“Title:”和“Author:”在所有 html 文件中都很常见。我想提取“Title:”和“Author:”旁边的文本。 我假设我使用漂亮的汤来提取每个 html 文件。但是要提取TitleAuthor,最好使用正则表达式吗?

【问题讨论】:

    标签: python html web-scraping beautifulsoup natural-language-processing


    【解决方案1】:

    别管漂亮的汤,用正则表达式就行了:

    re.findall(r'(?<=Author:).*?(?=<)', html.replace('\n', ''))
    >>> [' Mario Puzo']
    
    re.findall(r'(?<=Title:).*?(?=<)', html.replace('\n', ''))
    >>> [' The GodFatherAuthor: Mario Puzo']
    

    这将匹配作者,授予,它可能不适用于您的某些标题,因为它还在另一个标签之前包含“作者”(如上所示),在这种情况下,您可以为所有抓取的标题执行 title.split('Author')[0],因为如果Author 不在字符串中此方法不会改变字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多