Step2 - 代碼優(yōu)化
前文提要
- xiaolinBot(Twitter笑話集錦爬蟲Bot) Step0-概述
- xiaolinBot(Twitter笑話集錦爬蟲Bot) Step1-最簡(jiǎn)爬蟲
簡(jiǎn)介
這篇我們簡(jiǎn)要的討論一下代碼優(yōu)化渤早,這里主要討論兩點(diǎn)
- 過程到函數(shù)
- 加入對(duì)media的處理
- PEP8
我們?cè)赟tep1中的編碼是面向過程的嘴秸,這個(gè)不利于復(fù)用厉碟,所以我們簡(jiǎn)單的將我們前面的代碼函數(shù)化损离,方便以后擴(kuò)展及別人的調(diào)用
另外,Python代碼最好符合PEP8規(guī)范,方便自己和別人閱讀
編碼
創(chuàng)建 utils/common.py
import os
import requests
PROXIES = None
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)'
' AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/38.0.2125.122 Safari/537.36',
'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'
}
################################
#
# requests Operation
#
################################
def GetPage(url, proxies=PROXIES, headers=HEADERS):
r = requests.get(url, proxies=proxies, headers=headers)
assert r.status_code == 200
return r.text
def GetMedia(
url, proxies=PROXIES, headers=HEADERS, chunk_size=512,
media_type='pic'):
r = requests.get(url, proxies=proxies, headers=headers, stream=True)
filename = 'download/' + media_type + '/' + os.path.basename(url)
with open(filename, 'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
return filename
這里主要封裝了兩個(gè)方法: GetPage 與 GetMedia
GetPage: 傳入頁面url 獲得 整個(gè)頁面
GetMeida: 傳入圖片或者視頻的url, 下載媒體文件到 download/pic 或者 download/video(主要為了后續(xù)支持百思不得姐的視頻)
main.py 更改為:
# coding: utf-8
from pyquery import PyQuery as pq
from utils.common import GetMedia, GetPage
__author__ = 'BONFY CHEN <foreverbonfy@163.com>'
####################
#
# main function
#
####################
def qiushi():
url = 'http://www.qiushibaike.com/'
page = GetPage(url)
d = pq(page)
contents = d("div .article")
for item in contents:
i = pq(item)
pic_url = i("div .thumb img").attr.src
content = i("div .content").text()
id = i.attr.id
if pic_url:
pic_path = GetMedia(pic_url)
print('pic - {id}: {content} \\npic下載到{pic_path}'.format(
id=id, content=content, pic_path=pic_path))
else:
print('text - {id}: {content}'.format(id=id, content=content))
def main():
qiushi()
if __name__ == '__main__':
main()
運(yùn)行結(jié)果:
結(jié)果
PEP8
$ pip install pep8
$ pep8 xiaolinBot
然后如果有不符合規(guī)范的代碼践樱,會(huì)顯示提示扁誓,然后去更改就行了
PEP8
完整代碼
詳情見 https://github.com/bonfy/xiaolinBot
歡迎關(guān)注一起交流
下一篇已發(fā)布: xiaolinBot(Twitter笑話集錦爬蟲Bot) Step3-適配器