Python Web Scraping 数据提取


分析网页意味着了解其结构。现在,问题出现了,为什么它对网络抓取很重要?在本章中,让我们详细了解这一点。

网页分析


网页分析很重要,因为如果不进行分析,我们无法知道提取后我们将从(结构化或非结构化)该网页接收数据的形式。我们可以通过以下方式进行网页分析:

查看页面源

这是一种通过检查其源代码来了解网页结构的方法。要实现这一点,我们需要右键单击页面,然后必须选择 查看页面源代码 选项。然后,我们将从该网页以 HTML 的形式获取我们感兴趣的数据。但主要关注的是我们难以格式化的空格和格式化。

通过单击检查元素选项检查页面源

这是另一种分析网页的方法。但不同的是,它将解决网页源代码中的格式和空格问题。你可以通过右键单击然后选择 Inspect or 检查元素 菜单中的选项。它将提供有关该网页特定区域或元素的信息。

从网页中提取数据的不同方法


以下方法主要用于从网页中提取数据:

正则表达式

它们是嵌入在 Python 中的高度专业化的编程语言。我们可以通过 re Python的模块。它也称为 RE 或正则表达式或正则表达式模式。在正则表达式的帮助下,我们可以为我们想要从数据中匹配的可能的字符串集指定一些规则。

如果你想了解更多关于一般正则表达式的信息,请转到链接 https://www.newbiego.com/automata_theory/regular_expressions.htm 如果你想了解更多关于 Python 中的 re 模块或正则表达式的信息,你可以关注 链接 https://www.newbiego.com/python/python_reg_expressions.htm .

例子

在以下示例中,我们将从 http://example.webscraping.com 在正则表达式的帮助下匹配 的内容后。

import re
import urllib.request
response =
    urllib.request.urlopen('http:// example.webscraping.com/places/default/view/India-102')
html = response.read()
text = html.decode()
re.findall('<td class="w2p_fw">(.*?)</td>',text)

对应的输出将如下图所示:

[
    '<img src="/places/static/images/flags/in.png" />',
    '3,287,590 square kilometres',
    '1,173,108,018',
    'IN',
    'India',
    'New Delhi',
    '<a href="/places/default/continent/AS">AS</a>',
    '.in',
    'INR',
    'Rupee',
    '91',
    '######',
    '^(\\d{6})$',
    'enIN,hi,bn,te,mr,ta,ur,gu,kn,ml,or,pa,as,bh,sat,ks,ne,sd,kok,doi,mni,sit,sa,fr,lus,inc',
    '<div>
        <a href="/places/default/iso/CN">CN </a>
        <a href="/places/default/iso/NP">NP </a>
        <a href="/places/default/iso/MM">MM </a>
        <a href="/places/default/iso/BT">BT </a>
        <a href="/places/default/iso/PK">PK </a>
        <a href="/places/default/iso/BD">BD </a>
    </div>'
]

请注意,在上面的输出中,你可以使用正则表达式查看有关国家 India 的详细信息。

美丽的汤


假设我们想从网页中收集所有超链接,那么我们可以使用一个名为 BeautifulSoup 的解析器,可以在 https://www.crummy.com/software/BeautifulSoup/bs4/doc/。 简单来说,BeautifulSoup 是一个 Python 库,用于从 HTML 和 XML 文件中提取数据。它可以与请求一起使用,因为它需要输入(文档或 url)来创建汤对象,因为它本身无法获取网页。你可以使用以下 Python 脚本来收集网页的标题和超链接。

安装美丽的汤

使用 pip 命令,我们可以安装 美丽的汤 无论是在我们的虚拟环境中还是在全局安装中。

(base) D:\ProgramData>pip install bs4
Collecting bs4
    Downloading
https:// files.pythonhosted.org/packages/10/ed/7e8b97591f6f456174139ec089c769f89
a94a1a4025fe967691de971f314/bs4-0.0.1.tar.gz
Requirement already satisfied: beautifulsoup4 in d:\programdata\lib\sitepackages
(from bs4) (4.6.0)
Building wheels for collected packages: bs4
    Running setup.py bdist_wheel for bs4 ... done
    Stored in directory:
C:\Users\gaurav\AppData\Local\pip\Cache\wheels\a0\b0\b2\4f80b9456b87abedbc0bf2d
52235414c3467d8889be38dd472
Successfully built bs4
Installing collected packages: bs4
Successfully installed bs4-0.0.1

例子

请注意,在此示例中,我们扩展了使用 requests python 模块实现的上述示例。我们正在使用 r.text 用于创建一个汤对象,该对象将进一步用于获取网页标题等详细信息。

首先,我们需要导入必要的 Python 模块:

import requests
from bs4 import BeautifulSoup

在以下代码行中,我们使用 requests 为 url 发出 GET HTTP 请求: https://authoraditiagarwal.com/ 通过发出 GET 请求。

现在我们需要创建一个 Soup 对象如下:

soup = BeautifulSoup(r.text, 'lxml')
print (soup.title)
print (soup.title.text)

对应的输出将如下图所示:

<title>Learn and Grow with Aditi Agarwal</title>
Learn and Grow with Aditi Agarwal

Lxml


我们将要讨论的另一个用于 Web 抓取的 Python 库是 lxml。它是一个高性能的 HTML 和 XML 解析库。它相对快速和直接。你可以阅读更多关于它 https://lxml.de/。

安装 lxml

使用 pip 命令,我们可以安装 lxml 无论是在我们的虚拟环境中还是在全局安装中。

(base) D:\ProgramData>pip install lxml
Collecting lxml
    Downloading
https:// files.pythonhosted.org/packages/b9/55/bcc78c70e8ba30f51b5495eb0e
3e949aa06e4a2de55b3de53dc9fa9653fa/lxml-4.2.5-cp36-cp36m-win_amd64.whl
(3.
6MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 3.6MB 64kB/s
Installing collected packages: lxml
Successfully installed lxml-4.2.5

示例:使用 lxml 和请求进行数据提取

在下面的示例中,我们从网页中抓取特定元素 authoraditiagarwal.com 通过使用 lxml 和请求:

首先,我们需要从 lxml 库中导入 requests 和 html,如下所示:

import requests
from lxml import html 

现在我们需要提供要报废的网页的 url

现在我们需要提供路径 (Xpath) 到该网页的特定元素:

path = '// *[@id="panel-836-0-0-1"]/div/div/p[1]'
response = requests.get(url)
byte_string = response.content
source_code = html.fromstring(byte_string)
tree = source_code.xpath(path)
print(tree[0].text_content()) 

对应的输出将如下图所示:

The Sprint Burndown or the Iteration Burndown chart is a powerful tool to communicate
daily progress to the stakeholders. It tracks the completion of work for a given sprint
or an iteration. The horizontal axis represents the days within a Sprint. The vertical 
axis represents the hours remaining to complete the committed work.