知道創宇的爬蟲面試題
使用python編寫一個網站爬蟲程式,支援引數如下:
spider.py -u url -d deep -f logfile -l loglevel(1-5) --testself -thread number --dbfile filepath --key=”HTML5”
引數說明:
-u 指定爬蟲開始地址
-d 指定爬蟲深度
–thread 指定執行緒池大小,多執行緒爬取頁面,可選引數,預設10
–dbfile 存放結果資料到指定的資料庫(sqlite)檔案中
–key 頁面內的關鍵詞,獲取滿足該關鍵詞的網頁,可選引數,預設為所有頁面
-l 日誌記錄檔案記錄詳細程度,數字越大記錄越詳細,可選引數,預設spider.log
–testself 程式自測,可選引數
功能描述:
1、指定網站爬取指定深度的頁面,將包含指定關鍵詞的頁面內容存放到sqlite3資料庫檔案中
2、程式每隔10秒在螢幕上列印進度資訊
3、支援執行緒池機制,併發爬取網頁
4、程式碼需要詳盡的註釋,自己需要深刻理解該程式所涉及到的各類知識點
5、需要自己實現執行緒池
提示:
提示1:使用re urllib/urllib2 beautifulsoup/lxml2 threading optparse Queue sqlite3 logger doctest等模組
提示2:注意是“執行緒池”而不僅僅是多執行緒
提示3:爬取sina.com.cn兩級深度要能正常結束
建議程式可分階段,逐步完成編寫,例如:
版本1:Spider1.py -u url -d deep
版本2:
版本3:Spider3.py -u url -d deep -f logfile -l loglevel(1-5) --testself -thread number
版本4:剩下所有功能
1.解析命令列模組optparse(optparse現在不再更新了,更新版本叫 argparse)
def parse():
parser = OptionParser(
description="This script is used to crawl analyzing web!" )
# 在使用者請求幫助時列印它,並會格式化以適合當前終端寬度
parser.add_option("-u", "-url", dest="urlpth", action="store",
help="Path you want to fetch", metavar="www.sina.com.cn")
parser.add_option("-d", "-deep", dest="depth", action="store", type="int",
help="Url path's deep, default 1", default=1)
parser.add_option("-k", "-key", dest="key", action="store",
help="You want to query keywords, For example 'test'")
parser.add_option("-f", "-file", dest="logfile", action="store",
help="Record log file path and name, default spider.log",
default='spider.log'),
parser.add_option("-l", "-level", dest="loglevel", action="store",
type="int", help="Log file level, default 1(CRITICAL)",
default=1),
parser.add_option("-t", "-thread", dest="thread", action="store",
type="int", help="Specify the thread pool, default 10",
default=10),
parser.add_option("-q", "-dbfile", dest="dbpth", action="store",
help="Specify the the sqlite file directory and name, \
default test.db", metavar='test.db')
parser.add_option("-s", "-testself", dest="testself", action="store_true",
help="Test myself", default=False)
(options, args) = parser.parse_args()
return options
基本用法:
- 載入OptionParser類,新建物件: OptionParser()
- 新增選項: add_option(…)
- 引數解析: parse_args() 預設是使用 sys.argv[1:] 作為引數, 也可以傳遞一個命令列引數列表: parse_args(list).
add_option方法引數含義:
- dest:用於儲存輸入的臨時變數,其值通過options的屬性訪問
- help:用於生成幫助資訊
- action:指導程式遇到命令列引數怎麼樣處理,三種值可選。
- store:讀取引數,如果引數符合type要求,則將值傳遞給dest變數。強制要求後面提供引數
- store_true/store_false: 作為標記使用,設定dest變數的值為True或False。後面可以不跟參
- metavar:在列印幫助文字時使用的選項引數的替代值。
- default:給dest預設值
- type:檢查命令列引數資料型別,有string,int,float等
parse_args():
- options:它是一個物件,儲存有命令列引數值。只要知道命令列引數名,如 input,就可以訪問其對應的值:options.input
- args:它是沒被解析的命令列引數的列表。
參考連結:
https://www.jianshu.com/p/fef2d215b91d 【簡單易懂,argparse模組】
https://www.jianshu.com/p/bec089061742 【詳解optparse模組】
https://docs.python.org/3.7/library/optparse.html#optparse-tutorial【官網】