這篇文章主要介紹了Python實現的爬取豆瓣電影信息功能,結合具體實例形式分析了Python基於requests庫的爬蟲使用技巧,需要的朋友可以參考下
本文實例講述了Python實現的爬取豆瓣電影信息功能。分享給大家供大家參考,具體如下:
本案例的任務爲,爬取豆瓣電影top250的電影信息(包括序號、電影名稱、導演和主演、評分以及經典臺詞),並將信息作爲字典形式保存進txt文件。這裏只用到requests庫,沒有用到beautifulsoup庫
step1:首先獲取每一頁的源代碼,用requests.get函數獲取,爲了防止請求錯誤,使用try...except..
def getpage(url): try: res=requests.get(url) if res.status_code==200: return res.text return None except RequestException: return None
step2:做每一頁的網址解析,打開原網址https://movie.douban.com/top250?,查看網頁源代碼,可以看到每一個電影的源代碼都是從<li>開始,在</li>處結束,寫好正則表達式以後爬到的列表的每一條item都有五個元素,因此將其寫成字典的形式,這裏用到yield函數(關於yield函數的用法,廖老師的有一篇文章比較好懂https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/)
對單個網頁的進行解析的代碼如下:
def parsepage(html): pat=re.compile('<li>.*?<em class="">(.*?)</em>.*?<img width="100" alt="(.*?)" src=.*?<p class="">' +'(.*?)</p>.*?property="v:average">(.*?)</span>.*?<span class="inq">(.*?)</span>.*?</li>',re.S) items=re.findall(pat,html) for item in items: yield{ 'index':item[0], 'title':item[1], 'stars':item[2].strip(), 'score':item[3], 'concept':item[4] }
下面的代碼是將每一個item寫入文件,這裏encoding='utf-8' 和ensure_ascii=False都是使寫入文件時中文能保持不變,json.dumps可以將(字典)對象轉化成字符串(但前面要先import json),with open的第二個參數爲a,表示每次寫入時,是往後追加(續接),而不是後一次寫入將之前內容覆蓋,\n是指要每一次寫入一個item之後要換行。
def write_tofile(content): with open('doubanfilms.txt','a',encoding='utf-8' ) as f: f.write(json.dumps(content,ensure_ascii=False)+'\n') f.close()
最後,需要用循環語句將每一頁(共10頁)內容都進行以上操作。這裏,第二頁的網址就是在第一頁的url上加上一個start=25, 第三頁是加上start=50,也就是每一頁的start=爲25*i。最後一段代碼如下:
def main(): url="https://movie.douban.com/top250?" for i in range(0,9): url_i=url+'start='+str(25*i) html_i=getpage(url_i) for item in parsepage(html_i): print(item) write_tofile(item) if __name__ == '__main__': main()
當然,這一段代碼還有一種寫法:
def main(start): url="https://movie.douban.com/top250?start="+str(start) html=getpage(url) for item in parsepage(html): print(item) write_tofile(item) if __name__ == '__main__': for i in range(10): main(i*10)
如果想讓你的程序跑的更快,可以用多線程爬蟲(當然這裏其實沒有必要):
#在最開始加載Pool包 from multiprocessing import Pool #最後的執行段改爲: if __name__ == '__main__': for i in range(10): main(i*10) pool=Pool() #在循環外寫 pool.map(main,[i*10 for i in range (10)])
更多關於Python相關內容可查看本站專題:《Python Socket編程技巧總結》、《Python正則表達式用法總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧彙總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧彙總》
希望本文所述對大家Python程序設計有所幫助。