urllib+BeautifulSoup無登陸模式爬取豆瓣電影Top250

對於簡單的爬蟲任務,尤爲對於初學者,urllib+BeautifulSoup足以知足大部分的任務。html

一、urllib是Python3自帶的庫,不須要安裝,可是BeautifulSoup倒是須要安裝的。安裝方式:pip install beautifulsoup4python

其官方文檔中文版地址:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.htmlsql

二、爬取任務:爬取的內容爲每部電影的名字 導演 主演 年代 國家 類型 評分 評分人數數據庫

三、展現方法:(1)、直接打印 (2)、存到Mysql數據庫app

四、分析:函數

 網站佈局:一、Top250共10頁  每頁25部電影  網站格式:https://movie.douban.com/top250?start=[0,25,50,75,100,125,150,175,200,225] 每個數字表明一行
對其中一部電影進行分析:
<div class="hd">
                
                           <a href="https://movie.douban.com/subject/1292052/" class="">
                            <span class="title">肖申克的救贖</span>
                                    <span class="title"> / The Shawshank Redemption</span>
                                <span class="other"> / 月黑高飛(港)  /  刺激1995(臺)</span>
                        </a><span class="playable">[可播放]</span>
                    </div>
                    <div class="bd">
                        <p class="">
                            導演: 弗蘭克·德拉邦特 Frank Darabont   主演: 蒂姆·羅賓斯 Tim Robbins /...<br>
                            1994 / 美國 / 犯罪 劇情
                        </p>

                        
                        <div class="star">
                                <span class="rating5-t"></span>
                                <span class="rating_num" property="v:average">9.6</span>
                                <span property="v:best" content="10.0"></span>
                                <span>765942人評價</span>
                        </div>

                            <p class="quote">
                                <span class="inq">但願讓人自由。</span>
                            </p>
                    </div>
 

 主要部分在 div class='article'下的 ol class='grid_view'中的 li裏面。各個信息均可以在這裏面找到。佈局

《一》利用BeautifulSoup的find函數,能夠輕鬆的實現打印功能,保存到本地csv中:網站

代碼以下:url

#-*- encoding:utf-8 -*-
from urllib.request import urlopen
from bs4 import BeautifulSoup
from urllib.error import HTTPError
import re
import csv
####本程序爲爬取豆瓣電影Top250 ,先放在本地txt文檔中,後續放到Mysql中
####本程序爲bs4,後續改成Scrapy
###爬取的內容爲每部電影的名字 導演  主演  年代  國家  類型  評分  評分人數  。。。


"""分析部分: 網站佈局:一、Top250共10頁  每頁25部電影  網站格式:https://movie.douban.com/top250?start=

"""

def crawl(baseurl,bias):
	try:
		html=urlopen(baseurl+'?start=%d' %bias)
	except HTTPError:
		return None
	bsObj=BeautifulSoup(html,'lxml')
	totalContent=bsObj.find('ol',{'class':'grid_view'}).findAll('li')###每一頁25個電影的所有信息
	retList=[]
	for eachMovie  in totalContent:
		rank=eachMovie.em.get_text()  ###獲取排名
		href=eachMovie.a['href']     ####獲取到鏈接地址
		nameList=eachMovie.find_all('span',{'class':'title'})
		Chinesename=nameList[0].get_text()  ### 中文名字
		if(len(nameList)==2):
			Englishname=nameList[1].get_text()  ##英文名字
		else:
			Englishname="None"
		othername=eachMovie.find('span',{'class':'other'}).get_text().replace('/','')
		relate=eachMovie.find('p',{'class':''}).get_text().replace(' ','') ###主演,導演等信息  須要分割處理
		rating=eachMovie.find('span',{'class':'rating_num','property':'v:average'}).get_text()  ##評分
		starDiv=eachMovie.find('div',{'class':'star'})
		ratingN=starDiv.find_all('span')[3].get_text()
		ratingNum=re.split(r"\D",ratingN)[0]        ####評價的人數
		try:
			abstract=eachMovie.find('span',{'class':'inq'}).get_text()
		except AttributeError:
			abstract="None"
		OutputStr="排名: "+rank+'\t網址: '+href+'\t中文名: '+Chinesename+'\t英文名: '+Englishname+'\t別名: '+othername+\
				  '\t評分: '+rating+'\t評價人數: '+ratingNum+'\t摘要: '+abstract+"\t"+'相關信息:'+relate
		print(OutputStr)
		eachList=[rank,href,Chinesename,Englishname,othername,rating,ratingNum,abstract,relate]
		retList.append(eachList)
	return retList
def storeToCsv(AttributeList):
	csvFile=open('res.csv','a+',encoding='utf-8')
	try:
		writer=csv.writer(csvFile)
		writer.writerow(('排名',"網址",'中文名','英文名','別名','評分','評價人數','摘要','相關信息'))
		for i in range(10):
			for j in range(25):
				writer.writerow(AttributeList[i][j])
	finally:
		csvFile.close()



if __name__=='__main__':
	url='https://movie.douban.com/top250'
	biasList=[0,25,50,75,100,125,150,175,200,225]
	allList=[]
	for eachBias in biasList:
		s=crawl(url,eachBias)
		allList.append(s)
	storeToCsv(allList)

 

 運行結果以下圖:
 
相關文章
相關標籤/搜索