一、前言
2020-04-3日爬蟲練習
每日一個爬蟲小練習,學習爬蟲的記得關注哦!
學習編程就像學習騎自行車一樣,對新手來說最重要的是持之以恆的練習。
在《汲取地下水》這一章節中看見的一句話:“別擔心自己的才華或能力不足。持之以恆地練習,才華便會有所增長”,現在想來,真是如此。
最近在學習 數據解析之BeautifulSoup4庫 ,所以寫這篇爬蟲來練練手,鞏固知識點。
BeautifulSoup4知識點參考我博文:【爬蟲學的好,基礎少不了】:數據解析之BeautifulSoup4庫
二、需求:
爬取豆瓣電影TOP250,並儲存到本地CSV
三、技術路線:
技術路線:
1.requests
2.BeautifulSoup
四、爬蟲示例:
import requests
from bs4 import BeautifulSoup
import time
class Douban:
def __init__(self):
self.headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
'referer': 'https://movie.douban.com/cinema/nowplaying/wuhan/'
}
# 獲取分頁html
def get_html(self, url):
try:
result = requests.get(url=url, headers=self.headers)
result.raise_for_status() # 主動拋出一個異常
html = BeautifulSoup(result.text, 'lxml')
return html
except:
print('鏈接失敗!')
# 獲取電影url
def get_movie_url(self, html):
lis = html.find('ol', class_="grid_view").find_all('li')
for li in lis:
detail_url = li.find('a')['href']
yield detail_url
# 獲取電影相關信息 電影名、導演、編劇、主演、評分
def get_movie_info(self, movie_html):
# 電影名
titie = list(movie_html.find('h1').stripped_strings)
movie_name = ''.join(titie)
# 導演
director = movie_html.find('div', id="info").find('span', class_="attrs").string
# 編劇
screenwriter = list(movie_html.find('div', id='info').find_all('span')[3].find('span', class_='attrs').stripped_strings)
screenwriter = ''.join(screenwriter)
# 主演
actors = list(movie_html.find('span', class_="actor").find('span', class_='attrs').stripped_strings)
actors = ''.join(actors)
# 評分
grade = movie_html.find('strong', class_="ll rating_num").string
movie_infos = (movie_name, director, screenwriter, actors, grade)
yield movie_infos
# 保存電影信息到本地
def save_movies_info(self, movie_info, f):
f.write("{},{},{},{},{}\n".format(movie_info[0], movie_info[1], movie_info[2], movie_info[3], movie_info[4]))
print('保存:【{}】電影成功!'.format(movie_info[0]))
# 邏輯功能
def func(self, base_url):
# 將with open放在循環前的好處是避免每次循環寫入都需要重新打開,降低系統資源請求
with open('./res/DoubanTop250.csv', 'a', encoding='utf-8')as f:
for x in range(0, 250, 25):
# 加入異常處理,因爲有1-2部電影沒有主演,會導致抓取出錯,加上異常處理讓程序不中斷
try:
url = base_url.format(x) # 拼接分頁url
time.sleep(1) # 延時請求,避免請求速度過快被豆瓣反爬
html = self.get_html(url)
for detail_url in self.get_movie_url(html):
movie_html = self.get_html(detail_url)
for movie_info in self.get_movie_info(movie_html):
self.save_movies_info(movie_info, f)
except Exception as e:
print(e) # 打印異常類型
continue
if __name__ == '__main__':
obj = Douban()
obj.func('https://movie.douban.com/top250?start={}&filter=')