Python培訓入門 | python定期爬取GitHub上每日流行項目
介紹一個在GitHub上看到的通用的Python爬蟲,難度不大,是一個蠻好玩的點,順便總結一下Python爬蟲的一些需要注意的點。
先上鏈接:github源碼
1. 項目簡介
大家可以看一下這個網站 https://github.com/trending

隨時關注最新的技術動向,永遠是一個程序員應該做到的,但我們不能做到每天去查看,于是就誕生了這個repo(更正為原作者寫了這個repo),我們將爬蟲掛在Linux服務器上,定期爬取并且推送到自己的repo上,只要有時間,就可以看到之前的所有熱門項目。

順便說一句這樣是不是還可以刷一波GitHub commit
代碼po在了最后面
2. 關于Python的私人總結
使用Python開發(fā)爬蟲的時候需要注意哪些?
1.區(qū)分Python版本
Python 2.x 3.x 差別很大,如果遇到就編譯通不過,及早意識到進行修正還好,若是語法差別不大卻沒有意識到,有時候會給自己惹來很大的麻煩
2.關注幾種易于混淆的數(shù)據類型
- Tuples
- Lists
- Dictionary
- Json
需要格外關注這幾種類型之間的轉換,我們知道Python是一種弱數(shù)據類型語言,但不代表著它的數(shù)據類型可以混用,反而,正因為弱化了聲明,才讓有些操作更加容易出錯,這時候我們需要做的,就是仔細閱讀文檔,熟悉不同的用法。Tuples

Lists

Dictionary
推薦文檔:Tuples, Lists, and Dictionaries
3.注意合理使用第三方類庫
Python相對于java等語言,最大的優(yōu)勢就在于其具有很大規(guī)模的封裝良好的類庫,可以讓我們使用短短的幾行代碼,實現(xiàn)很多功能。這里列舉幾個常用的庫和框架:
- virtualenv 創(chuàng)建獨立 Python 環(huán)境的工具。
- Beautiful Soup 提供一些簡單的、Python式的函數(shù)用來處理導航、搜索、修改分析樹等功能 簡單的說就是解析網頁
- Scrapy 強大的爬蟲框架Scrapy
限于篇幅,放幾個鏈接大家自己進去看
哪些 Python 庫讓你相見恨晚?
Python 常用的標準庫以及第三方庫有哪些?
3. 代碼
下面是注釋版代碼,Python2.7 用了requests PyQuery等幾個類庫
代碼寫的比較明確了,就沒有過多注釋
#!/usr/local/bin/Python2.7
# coding:utf-8
import datetime
import codecs
import requests
import os
import time
from pyquery import PyQuery as pq
#git操作 推送到遠程repo
def git_add_commit_push(date, filename):
cmd_git_add = 'git add .'
cmd_git_commit = 'git commit -m "{date}"'.format(date=date)
cmd_git_push = 'git push -u origin master'
os.system(cmd_git_add)
os.system(cmd_git_commit)
os.system(cmd_git_push)
def createMarkdown(date, filename):
with open(filename, 'w') as f:
f.write("###" + date + "\n")
def scrape(language, filename):
HEADERS = {
'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0',
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding' : 'gzip,deflate,sdch',
'Accept-Language' : 'zh-CN,zh;q=0.8'
}
url = 'https://github.com/trending/{language}'.format(language=language)
r = requests.get(url, headers=HEADERS)
assert r.status_code == 200
# print(r.encoding)
d = pq(r.content)
items = d('ol.repo-list li')
# codecs to solve the problem utf-8 codec like chinese
with codecs.open(filename, "a", "utf-8") as f:
f.write('\n####{language}\n'.format(language=language))
for item in items:
i = pq(item)
title = i("h3 a").text()
owner = i("span.prefix").text()
description = i("p.col-9").text()
url = i("h3 a").attr("href")
url = "https://github.com" + url
# ownerImg = i("p.repo-list-meta a img").attr("src")
# print(ownerImg)
f.write(u"* [{title}]({url}):{description}\n".format(title=title, url=url, description=description))
#定時爬取對應語言的并寫入到markdown文本中
def job():
strdate = datetime.datetime.now().strftime('%Y-%m-%d')
filename = '{date}.md'.format(date=strdate)
# create markdown file
createMarkdown(strdate, filename)
# write markdown
scrape('Python', filename)
scrape('swift', filename)
scrape('javascript', filename)
scrape('go', filename)
scrape('Objective-C', filename)
scrape('Java', filename)
scrape('C++', filename)
scrape('C#', filename)
# git add commit push
git_add_commit_push(strdate, filename)
#主函數(shù)
if __name__ == '__main__':
while True:
job()
time.sleep(12 * 60 * 60)
4. 擴展及埋坑 下集預告
這里分享幾個Python相關的重要鏈接,看了一定會有收獲(尤其是前兩者),而且很大,沒效果你回來打我(匿
下面準備把oschina一個類似的東西一塊爬一下,push到repo里
接下來準備寫一個爬取學校教務系統(tǒng)驗證碼并訓練識別的文章,敬請期待。
- 資源匯總:Python框架、類庫、軟件和資源匯總repo
- 爬蟲集合:各種Python爬蟲集合
- Python爬蟲教程: 靜覓 崔慶才的個人博客
- Python學習路線: 知乎:如何入門 Python 爬蟲?
- 原repo go語言版本: github-trending
- Python版本: github-trending