Google線上深度學習神器Colab
阿新 • • 發佈:2020-12-24
- Colab是google最近推出的一項Python線上程式設計的免費服務, 有了它,不學Python程式設計的理由又少了一個
- Colab環境已經集成了流行的深度學習框架Tensorflow,並附贈了一個虛擬機器(
40GB
硬碟+2*2.30GHZ
CPU+12.72GB
記憶體),如果在國內無法訪問google的服務又不想科學Shang網, 可以考慮微軟推出的notebook- Colab的操作類似於jupyter notebook
- Colab如同使用 Google 文件或表格一樣儲存在Google雲端硬碟中,並且可以共享
1. Colab 執行終端命令
google為我們提供的Colab服務繫結一個Ubuntu虛擬機器(40GB硬碟+2*2.30GHZ CPU+12.72GB記憶體), 我們只要在Colab中輸入以
!
開頭的終端命令即可
- 檢視虛擬機器硬碟容量
!df -lh
40GB的硬碟
- 檢視cpu配置
!cat /proc/cpuinfo | grep model\ name
雙核處理器
- 檢視記憶體容量
!cat /proc/meminfo | grep MemTotal
12.72GB記憶體
- 安裝python依賴包
# 安裝requests, 爬蟲必備
!pip install requests
# 安裝 lxml, 解析xpath語法
!pip install lxml
- 安裝 git
# 將獲取的資料同步到github倉庫 !apt install git
2. 用Colab編寫線上爬蟲,並在線展示成果
線上編寫豆瓣電影爬蟲
!pip install lxml
import os
import requests
from lxml import etree
# 負責下載電影海報
def download_img(db_id, title, img_addr, headers):
# 如果不存在圖片資料夾,則自動建立
if os.path.exists("./Top250_movie_images/"):
pass
else:
os.makedirs("./Top250_movie_images/")
# 獲取圖片二進位制資料
image_data = requests.get(img_addr, headers=headers).content
# 設定海報存儲存的路徑和名稱
image_path = "./Top250_movie_images/" + db_id[0] + "_" + title[0] + '.jpg'
# 儲存海報圖片
with open(image_path, "wb+") as f:
f.write(image_data)
# 根據url獲取資料,並列印到螢幕上,並儲存為檔案
def get_movies_data(url, headers):
# 獲取頁面的響應內容
db_response = requests.get(url, headers=headers)
# 將獲得的原始碼轉換為etree
db_reponse_etree = etree.HTML(db_response.content)
# 提取所有電影資料
db_movie_items = db_reponse_etree.xpath('//*[@id="content"]/div/div[1]/ol/li/div[@class="item"]')
# 遍歷電影資料列表,
for db_movie_item in db_movie_items:
# 這裡用到了xpath的知識
db_id = db_movie_item.xpath('div[@class="pic"]/em/text()')
db_title = db_movie_item.xpath('div[@class="info"]/div[@class="hd"]/a/span[1]/text()')
db_score = db_movie_item.xpath('div[@class="info"]/div[@class="bd"]/div[@class="star"]/span[@class="rating_num"]/text()')
db_desc = db_movie_item.xpath('div[@class="info"]/div[@class="bd"]/p[@class="quote"]/span[@class="inq"]/text()')
db_img_addr = db_movie_item.xpath('div[@class="pic"]/a/img/@src')
print("編號:",db_id,"標題:",db_title, "評分:",db_score,"電影描述:", db_desc)
# a表示追加模式, b表示以二進位制方式寫入, + 表示如果檔案不存在則自動建立
with open("./douban_movie_top250.txt", "ab+") as f:
tmp_data = "編號:"+str(db_id)+"標題:"+str(db_title)+"評分:"+str(db_score)+"電影描述:"+ str(db_desc)+"\n"
f.write(tmp_data.encode("utf-8"))
db_img_addr = str(db_img_addr[0].replace("\'", ""))
download_img(db_id, db_title, db_img_addr, headers)
def main():
# 使用列表生成式,生成待爬取的頁面url的列表
urls = ["https://movie.douban.com/top250?start="+str(i*25) for i in range(10)]
# 設定請求頭
headers = {
# 設定使用者代理頭(為狼披上羊皮)
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
}
# 為避免重複執行程式,造成內容重複,這裡把上次的檔案清除(可跳過)
if os.path.isfile("./douban_movie_top250.txt"):
os.remove("./douban_movie_top250.txt")
# 從列表取出url進行爬取
for url in urls:
get_movies_data(url, headers)
if __name__