如果您要花时间浏览网页,您可能遇到的一项任务就是从HTML中删除可见的文本内容。

如果您使用的是Python,我们可以使用BeautifulSoup来完成此任务。

设置提取

首先,我们需要获取一些HTML。我将使用Troy Hunt最近关于“Collection#1”Data Breach的博客文章。

以下是您下载HTML的方法:

  1. import requests
  2. url = 'https: //www.troyhunt.com/the-773-million-record-collection-1-data-reach/'res =
  3. requests.geturl
  4. html_page = res.content

现在,我们有了HTML ..但是那里会有很多混乱。我们如何提取我们想要的信息?

创建 beautiful soup

我们将使用Beautiful Soup来解析HTML,如下所示:

  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html_page, 'html.parser')

找到文字

BeautifulSoup提供了一种从HTML中查找文本内容(即非HTML)的简单方法:

  1. text = soup.find_all(text=True)

但是,这将为我们提供一些我们不想要的信息。

查看以下语句的输出:

  1. set([t.parent.name for t in text])
  2. # {'label', 'h4', 'ol', '[document]', 'a', 'h1', 'noscript', 'span', 'header', 'ul', 'html', 'section', 'article', 'em', 'meta', 'title', 'body', 'aside', 'footer', 'div', 'form', 'nav', 'p', 'head', 'link', 'strong', 'h6', 'br', 'li', 'h3', 'h5', 'input', 'blockquote', 'main', 'script', 'figure'}

这里有一些我们可能不想要的项目:

[document]

  • noscript
  • header
  • html
  • meta
  • head
  • input
  • script

对于其他人,您应该检查以查看您想要的。

提取有价值的文字

现在我们可以看到我们的宝贵元素,我们可以构建我们的输出:

  1. output = ''
  2. blacklist = [
  3. '[document]',
  4. 'noscript',
  5. 'header',
  6. 'html',
  7. 'meta',
  8. 'head',
  9. 'input',
  10. 'script',
  11. # there may be more elements you don't want, such as "style", etc.
  12. ]
  13. for t in text:
  14. if t.parent.name not in blacklist:
  15. output += '{} '.format(t)

完整的脚本

最后,这是从网页获取文本的完整Python脚本:

  1. import requests
  2. from bs4 import BeautifulSoup
  3. url = 'https://www.troyhunt.com/the-773-million-record-collection-1-data-reach/'
  4. res = requests.get(url)
  5. html_page = res.content
  6. soup = BeautifulSoup(html_page, 'html.parser')
  7. text = soup.find_all(text=True)
  8. output = ''
  9. blacklist = [
  10. '[document]',
  11. 'noscript',
  12. 'header',
  13. 'html',
  14. 'meta',
  15. 'head',
  16. 'input',
  17. 'script',
  18. # there may be more elements you don't want, such as "style", etc.
  19. ]
  20. for t in text:
  21. if t.parent.name not in blacklist:
  22. output += '{} '.format(t)
  23. print(output)

改进

如果你output现在看,你会发现我们有一些我们不想要的东西。

标题中有一些文字:

  1. Home \n \n \n Workshops \n \n \n Speaking \n \n \n Media \n \n \n About \n \n \n Contact \n \n \n Sponsor \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n Sponsored by:

还有一些来自页脚的文字:

  1. \n \n \n \n \n \n Weekly Update 122 \n \n \n \n \n Weekly Update 121 \n \n \n \n \n \n \n \n Subscribe \n \n \n \n \n \n \n \n \n \n Subscribe Now! \n \n \n \n \r\n Send new blog posts: \n daily \n weekly \n \n \n \n Hey, just quickly confirm you\'re not a robot: \n Submitting... \n Got it! Check your email, click the confirmation link I just sent you and we\'re done. \n \n \n \n \n \n \n \n Copyright 2019, Troy Hunt \n This work is licensed under a Creative Commons Attribution 4.0 International License . In other words, share generously but provide attribution. \n \n \n Disclaimer \n Opinions expressed here are my own and may not reflect those of people I work with, my mates, my wife, the kids etc. Unless I\'m quoting someone, they\'re just my own views. \n \n \n Published with Ghost \n This site runs entirely on Ghost and is made possible thanks to their kind support. Read more about why I chose to use Ghost . \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n '

如果您只是从单个站点提取文本,您可以查看HTML并找到一种方法来仅从页面中解析出有价值的内容。

不幸的是,互联网是一个混乱的地方,你很难在HTML语义上找到共识。

祝好运!

原文来源:https://matix.io/extract-text-from-webpage-using-beautifulsoup-and-python/

[译]使用BeautifulSoup和Python从网页中提取文本的更多相关文章

  1. 第 3 章 HTML5 网页中的文本和图像

    文字和图像是网页中最主要.最常用的元素. 在互联网高速发展的今天,网站已经成为一个展示与宣传自我的通信工具(公司或个人可以通过网站介绍公司的服务与产品或介绍自己).这些都离不开网站中的网页,而网页的内 ...

  2. 使用 CSS 选择器从网页中提取数据

    在 R 中,关于网络爬虫最简单易用的扩展包是 rvest.运行以下代码从 CRAN 上安装:install.packages("rvest")首先,加载包并用 read_html( ...

  3. 如何使用免费PDF控件从PDF文档中提取文本和图片

             如何使用免费PDF控件从PDF文档中提取文本和图片 概要 现在手头的项目有一个需求是从PDF文档中提取文本和图片,我以前也使用过像iTextSharp, PDFBox 这些免费的PD ...

  4. 利用java从docx文档中提取文本内容

    利用java从docx文档中提取文本内容 使用Apache的第三方jar包,地址为https://poi.apache.org/ docx文档内容如图: 目录结构: 每个文件夹的名称为日期加上来源,例 ...

  5. 如何在网页中提取Email地址

    开博好久了,今天第一次发表技术文档,之前总是将一些好的事例保存在电脑,时间久了找起来也很麻烦,所以还是放在博客里进行归类比较方便,这样也能将自己在学习过程中的一些心得体会分享给大家,也能给需要的人一点 ...

  6. java从pdf中提取文本

    一(单文件转换):下载pdfbox包,百度搜pdfbox.(fontbox-1.8.16.jar和pdfbox-app-1.8.16.jar) package pdf; import java.io. ...

  7. 用PDFMiner从PDF中提取文本文字

    1.下载并安装PDFMiner 从https://pypi.python.org/pypi/pdfminer/下载PDFMineer wget https://pypi.python.org/pack ...

  8. 【python】网页中字符编码转换 unicode-escape

    有的时候我们用python来抓取网页会得到类似 '\\u003C\\u0066\\u0072\\u006F\\u006D\\u003E' 或者 '%u003c%u0062%u0072%u003e%u0 ...

  9. [python]获取网页中内容为汉字的字符串的判断

    实际上是这样,将获取到网页中表单内容与汉字字符串作比较,即: a = request.POST['a'] if a == '博客园': print 'ok' else: print 'false' a ...

随机推荐

  1. VMware15.5版本通过挂载系统光盘搭建yum仓库

    VMware15.5版本通过挂载系统光盘搭建yum仓库一.1.打开CentOS 7虚拟机. 2.登录虚拟机,选择未列出  用户名:root 密码:输入自己设置的密码 点击登录. 3.右键单击打开终端. ...

  2. Linux正则表达式、shell基础、文件查找及打包压缩

    Linux正则表达式.shell基础.文件查找及打包压缩 一.正则表达式 Linux正则表达式分为2类: 1.基本正则表达式(BRE) 2.扩展正则表达式(ERE) 两者的区别: 1.使用扩展正则表达 ...

  3. Python包模块化调用方式详解

    Python包模块化调用方式详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一般来说,编程语言中,库.包.模块是同一种概念,是代码组织方式. Python中只有一种模块对象类型 ...

  4. Python练习题——用列表的方法输出杨辉三角

    def main(): num = int(input('请输入行数: ')) yh = [[]] * num #创建num行空列表 for row in range(len(yh)): #遍历每一行 ...

  5. 批量插入实体类转化DataTable

    /// <summary> /// 根据实体类得到表结构 /// </summary> /// <param name="model">实体类& ...

  6. 应用安全测试技术DAST、SAST、IAST对比分析【转】

    转自:https://blog.csdn.net/qq_29277155/article/details/92411079 一.全球面临软件安全危机 2010年,大型社交网站rockyou.com被曝 ...

  7. AndroidStudio中Flutter打包APK

    1.生成签名文件 在打包之前我们需要一个签名文件,证明文件的唯一性. keytool -genkey -v -keystore F:\APP\sign.jks -keyalg RSA -keysize ...

  8. Greenplum 与 PostgreSQL 修改元数据(catalog)的方法 allow_system_table_mods

    背景 PostgreSQL大量的信息保存在元数据中,所有的元数据都是内部维护的,例如建表.建索引.删表等操作,自动维护元数据. 在某些迫不得已的情况下才可能需要直接对元数据进行修改. 默认情况下,用户 ...

  9. 如何把上传图片时候的文件对象转换为图片的url !

    getObjectURL(file) { var url = null; if (window.createObjectURL != undefined) { url = window.createO ...

  10. H5利用formData来上传文件(包括图片,doc,pdf等各种格式)方法小结!

    H5页面中我们常需要进行文件上传,那么怎么来实现这个功能呢??? 我主要谈如下两种方法. (一).传统的form表单方法 <form action="/Home/SaveFile1&q ...