1. 程式人生 > >python3 爬蟲抓取豆掰電影TOP 250

python3 爬蟲抓取豆掰電影TOP 250

個人喜歡看電影,就去爬豆瓣上的電影Top榜,python入門不久,順便學習練下

from urllib import request  
from bs4 import BeautifulSoup            #Beautiful Soup是一個可以從HTML或XML檔案中提取結構化資料的Python庫  
  
txt =''
top = 0
# 遍歷豆瓣網站,爬蟲分頁資料
for i in range(10):
	start =i*25
	#構造標頭檔案,模擬瀏覽器訪問  
	url="https://movie.douban.com/top250?start="+str(start) 
	headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}  
	page = request.Request(url,headers=headers)  
	page_info = request.urlopen(page).read().decode('utf-8')#開啟Url,獲取HttpResponse返回物件並讀取其ResposneBody  
	soup = BeautifulSoup(page_info ,'html.parser') #將html.parser作為解析器  
	info = soup.select('.info')

	for moive in info:
		top=top+1
		txt += 'Top'+str(top) + ' 電影名:'
		for title in moive.select('.hd .title'):
			txt += title.string
			pass
		
		txt += '  評分:'+moive.select('.bd .star .rating_num')[0].string
		txt +='\n\r' 

	#開啟一個檔案,window下需要加 utf-8 ,因為 新建立的檔案預設為gbk
	fo = open("movietop.txt", "w",encoding='utf-8')

	#寫入
	fo.write(txt)
	 
	# 關閉開啟的檔案
	fo.close()
#   


戰績:


github: https://github.com/a519395243/Python_Item/