網頁抓取(Web scraping)是一個非常實用的技術,能夠幫助我們讀取網頁內的資料然後加以利用,所以今次使用Python作一個簡單的抓取程式。
首先我們將需要抓取的網址放在urls.txt中,一行一個網址:
https://www.python.org/ https://www.google.com/ https://www.bloomberg.com/
程式碼將會讀取這個檔案,然後一行一行地處理。
然後看看抓取網頁的程式碼:
import urllib.request import time import os doc_folder = "files" if not os.path.exists(doc_folder): os.makedirs(doc_folder) with open('urls.txt') as my_urls: for my_url in my_urls: try: timestamp = str(int(round(time.time() * 1000))) print("Fetching URL: "+my_url.rstrip()) my_url_res = urllib.request.urlopen(my_url.rstrip()) my_url_raw = my_url_res.read() my_url_str = my_url_raw.decode("utf8") my_url_res.close() local_file = open('files/'+timestamp+'.txt','w+') local_file.write(my_url_str) local_file.close() except Exception as e: print('Exception: '+ str(e))
Python其中一個優點是簡潔,如果你是開發人員但未接觸過Python,相信只要點時間就可以明白。
首先我們引入需用的程式庫:
import urllib.request import time import os
urllib.request是用來讀取網頁之用,而time和os則是時間和系統相關的程式庫。
doc_folder = "files" if not os.path.exists(doc_folder): os.makedirs(doc_folder)
接著我們會建立一個資料夾,如果已經存在就會略過。
with open('urls.txt') as my_urls: for my_url in my_urls: try: timestamp = str(int(round(time.time() * 1000))) print("Fetching URL: "+my_url.rstrip()) my_url_res = urllib.request.urlopen(my_url.rstrip()) my_url_raw = my_url_res.read() my_url_str = my_url_raw.decode("utf8") my_url_res.close() local_file = open('files/'+timestamp+'.txt','w+') local_file.write(my_url_str) local_file.close() except Exception as e: print('Exception: '+ str(e))
這段是抓取的核心程式碼,首先用with… as去打開urls.txt,然後用for… in逐行讀取網址並儲存在my_url中。
接著我們用urllib.request.urlopen去打開網址,my_url.rstrip()能夠將my_url尾段的空格符號移除。
之後程式會讀取網頁的內容然後設定為UTF8編碼並儲存在my_url_str,接著在files資料夾中創建一個新的檔案並將網頁資料儲存到檔案中。
在這個例子中我們只是將網頁內容存入檔案,你可以根據不同狀況將讀取的網頁內容存入資料庫又或者抽取其中的一些數據。