Python Web Scraping 数据爬取

Python Web Scraping 数据爬取

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

网页分析

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

查看页面来源

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

通过点击检查元素选项来检查网页来源

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

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

以下方法主要用于从网页中爬取数据,即

正则表达式

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

如果你想了解更多关于正则表达式的信息,请访问https://www.tutorialspoint.com/automata_theory/regular_expressions.htm, 如果你想了解更多关于Python中的re模块或正则表达式的信息,你可以点击链接https://www.tutorialspoint.com/python/python_reg_expressions.htm 。

例子

在下面的例子中,我们将在用正则表达式的帮助下匹配<td>的内容后, 从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>'
]

观察一下,在上面的输出中,你可以通过使用正则表达式看到关于印度国家的详细信息。

BeautifulSoup

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

安装Beautiful Soup

使用 pip 命令,我们可以将 beautifulsoup 安装在我们的虚拟环境或全局安装中。

(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

例子

请注意,在这个例子中,我们正在扩展上述用request python模块实现的例子。我们正在使用 r. text 来创建一个汤对象,它将进一步被用来获取网页的标题等细节。

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

import requests
from bs4 import BeautifulSoup

在下面这行代码中,我们使用request对url:https://authoraditiagarwal.com/进行GET HTTP请求。

r = requests.get('<https://authoraditiagarwal.com/>')

现在我们需要创建一个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

我们要讨论的另一个用于网络爬虫的 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和request爬取数据

在下面的例子中,我们通过使用lxml和request从 authoraditiagarwal.com 中爬取网页的一个特定元素-

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

import requests
from lxml import html 

现在,我们需要提供网页的网址来进行爬虫

url = ['https://authoraditiagarwal.com/leadershipmanagement/']('https://authoraditiagarwal.com/leadershipmanagement/)

现在我们需要提供通往该网页特定元素的(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.

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程