Python3爬虫项目集:豆瓣电影排行榜top250
生活随笔
收集整理的這篇文章主要介紹了
Python3爬虫项目集:豆瓣电影排行榜top250
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 前言
- 爬蟲概要
- 解析
- 代碼示例
- 數據存儲
Github地址:https://github.com/pasca520/Python3SpiderSet
前言
關于整理日常練習的一些爬蟲小練習,可用作學習使用。
爬取項目以學習為主,盡可能使用更多的模塊進行練習,而不是最優解。
爬蟲概要
| 爬取模塊 | request |
| 解析模塊 | BeautifulSoup |
| 存儲類型 | list(方便存入數據庫) |
解析
BeautifulSoup參數我整理的一篇文章:https://blog.csdn.net/qinglianchen0851/article/details/102860741
代碼示例
# -*- coding: utf-8 -*-import requests from requests.exceptions import ReadTimeout, ConnectionError, RequestException from bs4 import BeautifulSoup# 爬蟲主體 def get_page(url):headers = {'Connection': 'keep-alive','Cache-Control': 'max-age=0','User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36','Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3','Referer': 'https://maoyan.com/board',}try:response = requests.get(url=url, headers=headers).textreturn responseexcept ReadTimeout: # 訪問超時的錯誤print('Timeout')except ConnectionError: # 網絡中斷連接錯誤print('Connect error')except RequestException: # 父類錯誤print('Error')# 解析網頁 def parse_page(html):soup = BeautifulSoup(html, 'lxml')grid = soup.find(name="ol", attrs={"class": "grid_view"})movie_list = grid.find_all("li")for movie in movie_list:rank = movie.find(name="em").getText()name = movie.find(name="span", attrs={"class": "title"}).getText()rating_num = movie.find(name="span", attrs={"class": "rating_num"}).getText()# bd = movie.find(name="p").getText().strip().replace(' ', '\n').replace('...\n ', '...\n').replace(' / ', '\n').split('\n') # 頭皮發麻字符串分解系列,因為練習沒用 re,果然原生字符串處理麻煩的一匹,strip去除空格,replace替換,旨在將不同信息分類存儲到不同的參數,如導演、主演、上映時間、上映時間和電影類型bd = movie.find(name="p").getText().strip().replace(' ', '\n').replace('...\n ', '...\n').replace(' / ', '\n').split('\n') # 頭皮發麻字符串分解系列,因為練習沒用 re,果然原生字符串處理麻煩的一匹,strip去除空格,replace替換,旨在將不同信息分類存儲到不同的參數,如導演、主演、上映時間、上映時間和電影類型# 豆瓣有些主演沒有。。。賊蛋疼,為了簡便只能寫個爛代碼再增加一次了if len(bd) == 4:bd.insert(1, '沒爬到')inq = movie.find(name="span", attrs={"class": "inq"})# 處理 inq 為空的情況if not inq:inq = "暫無"else:inq = inq.getText()# 這里直接存儲到字典,方便存到數據庫douBanDict['rank'] = rankdouBanDict['name'] = namedouBanDict['director'] = bd[0]douBanDict['actor'] = bd[1]douBanDict['release_time'] = bd[2].strip() # 某些列表有空格,直接strip()去除空格douBanDict['country'] = bd[3]douBanDict['movie_types'] = bd[4]douBanDict['rating_num'] = rating_numdouBanDict['inq'] = inqdouBanList.append(str(douBanDict)) # 字典先轉為字符串再累加到列表中,否則無法字典值會一直變return douBanListif __name__ == '__main__':douBanList = []douBanDict = {}for start in range(0, 250, 25):url = 'https://movie.douban.com/top250?start={}&filter='.format(start)html = get_page(url)douBanList = parse_page(html)print(douBanList)數據存儲
直接是列表格式,同時包含各個電影信息的字典。
done!
總結
以上是生活随笔為你收集整理的Python3爬虫项目集:豆瓣电影排行榜top250的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蓝桥杯2015年第六届C/C++省赛A组
- 下一篇: 2022-2028年中国环保减速机行业运