1. 程式人生 > 實用技巧 >乾貨分享!網路爬蟲,提取網站資料。

乾貨分享!網路爬蟲,提取網站資料。

1 什麼是網路爬蟲 網路爬蟲是指從網站提取資料的技術,該技術可以將非結構化資料轉換為結構化資料。 網路爬蟲的用途是從網站提取資料,提取的資料可以儲存到本地檔案並儲存在系統中,也可以將其以表格的形式儲存到資料庫中。網路爬蟲使用HTTP或Web瀏覽器直接訪問全球資訊網(WWW)。網路爬蟲或機器人抓取網頁的過程是一個自動化流程。 抓取網頁的過程分為獲取網頁、提取資料。Web抓取程式可以獲取網頁,它是網路爬蟲的必需元件。在獲取網頁後,就需要提取網頁資料了。我們可以搜尋、解析,並將提取的資料儲存到表格中,然後重新整理格式。 2 資料提取 本節我們學習資料提取。我們可以使用Python的BeautifulSoup庫進行資料提取。這裡還需要用到Python庫的Requests模組。 執行以下命令以安裝Requests和BeautifulSoup庫。
$ pip3 install requests
$ pip3 install beautifulsoup4

2.1 Requests庫 使用Requests庫可以易懂的格式在Python指令碼中使用HTTP,這裡使用Python中的Requests庫獲取網頁。Requests庫包含不同型別的請求,這裡使用GET請求。GET請求用於從Web伺服器獲取資訊,使用GET請求可以獲取指定網頁的HTML內容。每個請求都對應一個狀態碼,狀態碼從伺服器返回,這些狀態碼為我們提供了對應請求執行結果的相關資訊。以下是部分狀態碼。

301:表示如果伺服器已切換域名或必須更改端點名稱,則伺服器將重定向到其他端點。

400:表示使用者發出了錯誤請求。

401:表示使用者未通過身份驗證。

403:表示使用者正在嘗試訪問禁用的資源。

404:表示使用者嘗試訪問的資源在伺服器上不可用。

2.2 BeautifulSoup庫 BeautifulSoup也是一個Python庫,它包含簡單的搜尋、導航和修改方法。它只是一個工具包,用於從網頁中提取所需的資料。 要在指令碼中使用Requests和BeautifulSoup模組,必須使用import語句匯入這兩個模組。現在我們來看一個解析網頁的示例程式,這裡將解析一個來自百度網站的新聞網頁。建立一個指令碼,命名為parse_web_page.py,並在其中寫入以下程式碼。
import requests
from bs4 import BeautifulSoup page_result = requests.get('https://www.news.baidu.com') parse_obj = BeautifulSoup(page_result.content, 'html.parser') print(parse_obj)

執行指令碼程式,如下所示。
student@ubuntu:~/work$ python3 parse_web_page.py
Output:<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml
" xmlns:og="http://ogp.me/ns#"> <head> <meta charset="utf-8"/> <meta content="IE=edge" http-equiv="X-UA-Compatible"/> <meta content="app-id=342792525, app-argument=imdb:///?src=mdot" name="apple-itunes-app"/> <script type="text/javascript">var IMDbTimer={starttime: new Date().getTime(),pt:'java'};</script> <script> if (typeof uet == 'function') { uet("bb", "LoadTitle", {wb: 1}); } </script> <script>(function(t){ (t.events = t.events || {})["csm_head_pre_title"] = new Date().getTime(); })(IMDbTimer);</script> <title>Top News - IMDb</title> <script>(function(t){ (t.events = t.events || {})["csm_head_post_title"] = new Date().getTime(); })(IMDbTimer);</script> <script> if (typeof uet == 'function') { uet("be", "LoadTitle", {wb: 1}); } </script> <script> if (typeof uex == 'function') { uex("ld", "LoadTitle", {wb: 1}); } </script> <link href="https://www.imdb.com/news/top" rel="canonical"/> <meta content="http://www.imdb.com/news/top" property="og:url"> <script> if (typeof uet == 'function') { uet("bb", "LoadIcons", {wb: 1}); }

上面的示例程式抓取了一個網頁,並使用BeautifulSoup對其進行了解析。首先匯入了requests和BeautifulSoup模組,然後使用GET請求訪問URL,並將結果分配給page_result變數,接著建立了一個BeautifulSoup物件parse_obj,此物件將requests的返回結果page_result.content作為引數,然後使用html.parser解析該頁面。 現在我們將從類和標籤中提取資料。轉到Web瀏覽器,右擊要提取的內容並向下查詢,找到“檢查”選項,單擊它將獲得類名。在程式中指定這個類名,並執行指令碼。建立一個指令碼,命名為extract_from_class.py,並在其中寫入以下程式碼。
import requests
from bs4 import BeautifulSoup
page_result = requests.get('https://www.news.baidu.com')
parse_obj = BeautifulSoup(page_result.content, 'html.parser')
top_news = parse_obj.find(class_='news-article__content')
print(top_news)

執行指令碼程式,如下所示。
student@ubuntu:~/work$ python3 extract_from_class.py
Output :<div class="news-article__content">
<a href="/name/nm4793987/">Issa Rae</a> and <a
href="/name/nm0000368/">Laura Dern</a> are teaming up to star in a limited
series called "The Dolls" currently in development at <a
href="/company/co0700043/">HBO</a>.<br/><br/>Inspired by true events, the
series recounts the aftermath of Christmas Eve riots in two small Arkansastowns in 1983, riots which erupted over Cabbage Patch Dolls. The seriesexplores class, race, privilege and what it takes to be a "goodmother."<br/><br/>Rae will serve as a writer and executive producer on the
series in addition to starring, with Dern also executive producing. <a
href="/name/nm3308450/">Laura Kittrell</a> and <a
href="/name/nm4276354/">Amy Aniobi</a> will also serve as writers and coexecutive
producers. <a href="/name/nm0501536/">Jayme Lemons</a> of Dern’s
<a href="/company/co0641481/">Jaywalker Pictures</a> and <a
href="/name/nm3973260/">Deniese Davis</a> of <a
href="/company/co0363033/">Issa Rae Productions</a> will also executive
produce.<br/><br/>Both Rae and Dern currently star in HBO shows, with Dern
appearing in the acclaimed drama "<a href="/title/tt3920596/">Big Little
Lies</a>" and Rae starring in and having created the hit comedy "<a
href="/title/tt5024912/">Insecure</a>." Dern also recently starred in the
film "<a href="/title/tt4015500/">The Tale</a>,
</div>

上面的示例程式首先匯入了requests和BeautifulSoup模組,然後建立了一個requests物件併為其分配了一個URL,接著建立了一個BeautifulSoup物件parse_obj。此物件將requests的返回結果page_result.content作為引數,然後使用html.parser解析頁面。最後,使用BeautifulSoup的find()方法從news-article__content類中獲取內容。 現在我們來看一個從特定標籤中提取資料的示例程式,此示例程式將從<a>標籤中提取資料。建立一個指令碼,命名為extract_from_tag.py,並在其中寫入以下程式碼。
import requests
from bs4 import BeautifulSoup
page_result = requests.get('https://www.news.baidu.com/news')
parse_obj = BeautifulSoup(page_result.content, 'html.parser')
top_news = parse_obj.find(class_='news-article__content')
top_news_a_content = top_news.find_all('a')
print(top_news_a_content)

執行指令碼程式,如下所示。
student@ubuntu:~/work$ python3 extract_from_tag.py
Output:[<a href="/name/nm4793987/">Issa Rae</a>, <a href="/name/nm0000368/">Laura
Dern</a>, <a href="/company/co0700043/">HBO</a>, <a
href="/name/nm3308450/">Laura Kittrell</a>, <a href="/name/nm4276354/">Amy
Aniobi</a>, <a href="/name/nm0501536/">Jayme Lemons</a>, <a
href="/company/co0641481/">Jaywalker Pictures</a>, <a
href="/name/nm3973260/">Deniese Davis</a>, <a
href="/company/co0363033/">Issa Rae Productions</a>, <a
href="/title/tt3920596/">Big Little Lies</a>, <a
href="/title/tt5024912/">Insecure</a>, <a href="/title/tt4015500/">The
Tale</a>]

上面的示例程式從<a>標籤中提取資料。這裡使用find_all()方法從news-article__content類中提取所有<a>標籤資料。 3 從維基百科網站抓取資訊 本節我們將學習一個從維基百科網站獲取舞蹈種類列表的示例程式,這裡將列出所有古典印度舞蹈。建立一個指令碼,命名為extract_from_wikipedia.py,並在其中寫入以下程式碼。
import requests
from bs4 import BeautifulSoup
page_result = requests.get('https://en.wikipedia.org/wiki/Portal:History')
parse_obj = BeautifulSoup(page_result.content, 'html.parser')
h_obj = parse_obj.find(class_='hlist noprint')
h_obj_a_content = h_obj.find_all('a')
print(h_obj)
print(h_obj_a_content)
執行指令碼程式,如下所示。
student@ubuntu:~/work$ python3 extract_from_wikipedia.py
輸出如下。
<div class="hlist noprint" id="portals-browsebar" style="text-align:
center;">
<dl><dt><a href="/wiki/Portal:Contents/Portals"
title="Portal:Contents/Portals">Portal topics</a></dt>
<dd><a href="/wiki/Portal:Contents/Portals#Human_activities"
title="Portal:Contents/Portals">Activities</a></dd>
<dd><a href="/wiki/Portal:Contents/Portals#Culture_and_the_arts"
title="Portal:Contents/Portals">Culture</a></dd>
<dd><a href="/wiki/Portal:Contents/Portals#Geography_and_places"
title="Portal:Contents/Portals">Geography</a></dd>
<dd><a href="/wiki/Portal:Contents/Portals#Health_and_fitness"
title="Portal:Contents/Portals">Health</a></dd>
<dd><a href="/wiki/Portal:Contents/Portals#History_and_events"
title="Portal:Contents/Portals">History</a></dd>
<dd><a href="/wiki/Portal:Contents/Portals#Mathematics_and_logic"
title="Portal:Contents/Portals">Mathematics</a></dd>
<dd><a href="/wiki/Portal:Contents/Portals#Natural_and_physical_sciences"
title="Portal:Contents/Portals">Nature</a></dd>
<dd><a href="/wiki/Portal:Contents/Portals#People_and_self"
title="Portal:Contents/Portals">People</a></dd>
In the preceding example, we extracted the content from Wikipedia. In this
example also, we extracted the content from class as well as tag.
....