薅谷歌爸爸羊毛第一集 - 在Colab上运行Python代码

为什么使用Colab

  • 免费GPU提供超大算力和显存,尤其是最近谷歌爸爸把Colab的GPU从古董级别的K80全面升级成Tesla T4后好像更牛逼了
  • 融合了Jupyter使得Colab可视化十分友好
  • 和Google Drive的连接提供了高效的云存储和团队协作解决方案(比如当用Colab运行爬虫的时候可以将结果直接存储到GoogleDrive的文件夹里,如果你将这个文件夹与Boss共享,Boss就可以实时Check程序运行结果)
  • 是时候薅一波谷歌爸爸的羊毛了

如何配置Colab

从 https://colab.research.google.com/notebooks/welcome.ipynb 进入Colab后,记得 runtime -> changeruntimetype -> hardware accelerator -> GPU,就可以用上谷歌爸爸免费送的GPU加速啦。

薅羊毛攻略

Step1 : 授权登录
首先登录GoogleDrive,然后在Colab中运行如下代码,然后Colab会给出验证码链接,打开后粘到方框中回车即可。

from google.colab import files
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

# 授权登录
def login_google_drive():
  auth.authenticate_user()
  gauth = GoogleAuth()
  gauth.credentials = GoogleCredentials.get_application_default()
  drive = GoogleDrive(gauth)
  return drive
    
drive = login_google_drive()

在这里插入图片描述
Step 2: 指定文件夹并缓存代码中要用的文件

import os
from google.colab import drive

drive.mount('/content/drive')
path = "/content/drive/My Drive/parseins"

os.chdir(path)
os.listdir(path)

def list_file(drive):
  file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
  for file1 in file_list:
    print('title: %s, id: %s, mimeType: %s' % (file1['title'], file1['id'], file1["mimeType"]))
list_file(drive)

def cache_data():
  # id 替换成上一步读取到的对应文件 id
  acclist = drive.CreateFile({'id': "1sCDAXwmPPLem4M_vY4RQdQ_PBVbFMqXb"}) 
  #berlinstagram_postlist = drive.CreateFile({'id': "1-8Cn1LyoFXQIknyXoH8eksOw_2yYbX8M"}) 
  #这里的下载操作只是缓存,不会在你的Google Drive 目录下多下载一个文件
  
  acclist.GetContentFile('acclist.txt', "text/plain")
  #berlinstagram_postlist.GetContentFile('berlinstagram_postlist.csv', "text/csv")
  
  print("缓存成功")
  
cache_data()

Step 3: 安装代码中用到的module

!pip install requests
!pip install pyquery
!pip install pandas
!pip install PyDrive

Step 4: 将主程序放入Colab中并执行

注意事项

  • Colab最多连续运行12个小时,超过12个小时需要重新GoogleDrive授权
  • 因为随机分配GPU,所以要记得对自己的运行结果进行妥善保存
  • GPU更换后可能需要重新加载module和指定文件夹等

主要参考链接

  1. https://blog.csdn.net/linhai1028/article/details/79275945
  2. https://blog.csdn.net/linhai1028/article/details/79275945
  3. https://blog.csdn.net/heliucs/article/details/84644372
  4. https://blog.csdn.net/cocoaqin/article/details/79184540
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章