??大家好,我是不溫卜火,是一名計算機學院大資料專業大三的學生,昵稱來源于成語—
不溫不火,本意是希望自己性情溫和,作為一名互聯網行業的小白,博主寫博客一方面是為了記錄自己的學習程序,另一方面是總結自己所犯的錯誤希望能夠幫助到很多和自己一樣處于起步階段的萌新,但由于水平有限,博客中難免會有一些錯誤出現,有紕漏之處懇請各位大佬不吝賜教!暫時只在csdn這一個平臺進行更新,博客主頁:https://buwenbuhuo.blog.csdn.net/,
PS:由于現在越來越多的人未經本人同意直接爬取博主本人文章,博主在此特別宣告:未經本人允許,禁止轉載!!!
目錄
- 一、小小課堂
- 二、大體程序分析
- 三、具體細節分析
- 3.1 先獲取整個網頁的原始碼
- 3.2 獲取分類
- 3.3 獲取一頁的所有資料
- 3.4 回圈獲取所有URL及內容
- 3.5 得到資料
- 四、完整原始碼
- 五、保存完成結果

一、小小課堂

在古代,每當你閑暇之時,會同老友幾人一起吃酒喝茶,觥籌交錯,暢所欲言!而在如今,我們在無聊之時,又正值好友幾人閑暇之時,可能會同去看當下最新的電影,但是如果只有我們自己一人,這時的你會怎如何做呢?
如果是我的話,我就會先自行查看豆瓣電影的評分,從中選擇自己感興趣的影片進行觀看,這樣不僅節省了我們的時間,更能陶冶我們的情操,同時我們還能在觀影之后,查看別人給出的影評,從中給出中肯的評價,好為別人提供價值標桿,

好吧,說了那么多其實就是為了引出我們今天這篇博文所要爬取的網站——《豆瓣電影》,-,-
由于咱是技術博主,所以這些文鄒鄒的話咱就不寫了哈,
以往的博文,大都是講解的怎樣爬取靜態網頁,這不,本篇博文博主專門選擇了動態網頁豆瓣電影進行資料采集,
所謂動態網頁加載是通過js的ajax加載的資料或js演算法(加密)得到的資料,并不是直接可以得到的資料結果,
豆瓣電影這個網站是通過ajax加載的資料,為什么會這樣說呢?一會兒在分析網頁結構的時候,博主會進行解釋!
二、大體程序分析
在此,先給出豆瓣電影的URL:https://movie.douban.com/chart
-
1. 分析獲取的URL

-
2. 單擊分類資訊,跳轉到分類電影串列


這個頁面是有多頁資料加載的,當用戶向下滾動右側的滾動,加載資料,這個經過分析是ajax加載的資料,需要找到ajax請求的網址,

先找到分類,提取分類的名字和型別編號,然后再爬分類下的電影資料, -
2.提取資料的方法
ajax回傳的資料是json,response.json()得到的是字典,用字典操作就可以了,當然用正則是肯定可以的,其實專門操作json的有一個模塊叫jsonpath,
三、具體細節分析
3.1 先獲取整個網頁的原始碼
import requests
from lxml import etree
type_url = "https://movie.douban.com/chart"
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
}
def parse_url(url):
"""決議url,得到html"""
response = requests.get(url=url, headers=headers)
return response.content.decode("utf-8")
def parse_html(html):
"""決議url,得到字典"""
etree_obj = etree.HTML(html)
return etree_obj
content = parse_url(type_url)
print(content)

3.2 獲取分類
我們首先先看下網頁記憶體在iframe沒有

由于有iframe 所以不能使用xpath
下面我們先來看下我們所要爬取分類的格式

我們可以看到其格式為<a href="/typerank?type_name=劇情&type=11&interval_id=100:90&action=">劇情</a>
既然xpath不能使用,那么我們就使用正則進行決議
<a href="/typerank?type_name=劇情&type=11&interval_id=100:90&action=">劇情</a>
r'<a href="/typerank\?type_name=(.*?)&type=(\d+)&interval_id=100:90&action=">.*?</a>'

🆗,我們已經成功拿到電影的分類,下面開始嘗試拿到其中一個分類中的所有資料
3.3 獲取一頁的所有資料
movie_url = "https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=0&limit=20"
response = requests.get(url=movie_url,headers=headers)
content = response.json()
print(content)

3.4 回圈獲取所有URL及內容
我們先看下地址欄的URL


URL對比
https://movie.douban.com/typerank?type_name=%E5%89%A7%E6%83%85%E7%89%87&type=11&interval_id=100:90&action=
https://movie.douban.com/typerank?type_name=%E5%89%A7%E6%83%85%E7%89%87&type=11&interval_id=90:80&action=
我們可以看到其中的interval_id是以10為單位移動的,那么我們是不是能夠有一個大膽的想法能否拼接這個網址,然后回圈爬取內容么呢?
答案是可以的,在此博主就不多講解了,直接給出代碼
movie_url = "https://movie.douban.com/j/chart/top_list"
def get_movie(movie_type, low_score, high_score):
"""獲取電影"""
movie_type_name = movie_type[0]
movie_type_num = movie_type[1]
print(movie_type_num)
i = 0
while True:
# 引數
params = {
"type": movie_type_num,
"interval_id": "{}:{}".format(high_score, low_score),
"action": "",
"start": i,
"limit": 20
}
# 發請求獲取資料
content = parse_json(movie_url, params)
print(content)
exit()
def start():
"""爬蟲開始"""
low_score = int(input("輸入要爬取的最低分(以5為單位),最高分默認是加10>"))
high_score = low_score + 10
movie_type_list = get_movie_type()
for movie_type in movie_type_list:
get_movie(movie_type, low_score, high_score)
if __name__ == '__main__':
start()

3.5 得到資料
至于此部分只是單純的提取JSON中的資料,在此就不多解釋了

def get_movie(movie_type, low_score, high_score):
"""獲取電影"""
movie = {
"title": "", # 電影名稱
"actors": "", # 主演
"release_date": "", # 上映日期
"regions": "", # 上映地
"types": "", # 型別
"score": "", # 評分
"vote_count": "", # 評論數
"url": "", # url
}
movie_type_name = movie_type[0]
movie_type_num = movie_type[1]
i = 0
while True:
# 引數
params = {
"type": movie_type_num,
"interval_id": "{}:{}".format(high_score, low_score),
"action": "",
"start": i,
"limit": 20
}
# 發請求獲取資料
data_list = parse_json(movie_url, params)
# 判斷回圈退出
if not data_list:
break
# 回圈
for data in data_list:
movie["title"] = data["title"]
movie["actors"] = data["actors"]
movie["release_date"] = data["release_date"]
movie["regions"] = data["regions"]
movie["types"] = data["types"]
movie["score"] = data["score"]
movie["vote_count"] = data["vote_count"]
movie["url"] = data["url"]
save(movie)
i += 20
四、完整原始碼
# encoding: utf-8
'''
@author 李華鑫
@create 2020-10-09 8:27
Mycsdn:https://buwenbuhuo.blog.csdn.net/
@contact: 459804692@qq.com
@software: Pycharm
@file: 豆瓣電影.py
@Version:1.0
'''
import requests
import time
import re
import random
import csv
from lxml import etree
type_url = "https://movie.douban.com/chart"
movie_url = "https://movie.douban.com/j/chart/top_list"
headers = {
"user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
}
def parse_html(url, params={}):
"""決議url,得到html"""
response = requests.get(url=url, headers=headers, params=params)
return response.content.decode("utf-8")
def parse_json(url, params={}):
"""決議url,得到字典"""
response = requests.get(url=url, headers=headers, params=params)
return response.json()
def get_movie_type():
"""獲取電影分類"""
content = parse_html(type_url)
return re.findall(r'<a href="/typerank\?type_name=(.*?)&type=(\d+)&interval_id=100:90&action=">.*?</a>', content)
def get_movie(movie_type, low_score, high_score):
"""獲取電影"""
movie = {
"title": "", # 電影名稱
"actors": "", # 主演
"release_date": "", # 上映日期
"regions": "", # 上映地
"types": "", # 型別
"score": "", # 評分
"vote_count": "", # 評論數
"url": "", # url
}
movie_type_name = movie_type[0]
movie_type_num = movie_type[1]
i = 0
while True:
# 引數
params = {
"type": movie_type_num,
"interval_id": "{}:{}".format(high_score, low_score),
"action": "",
"start": i,
"limit": 20
}
# 發請求獲取資料
data_list = parse_json(movie_url, params)
# 判斷回圈退出
if not data_list:
break
# 回圈
for data in data_list:
movie["title"] = data["title"]
movie["actors"] = data["actors"]
movie["release_date"] = data["release_date"]
movie["regions"] = data["regions"] # 國家
movie["types"] = data["types"] # 型別
movie["score"] = data["score"] # 評分
movie["vote_count"] = data["vote_count"] # 評論條數
movie["url"] = data["url"] # url
save(movie)
i += 20
def save(item):
"""將資料保存到csv中"""
with open("./豆瓣電影.csv", "a", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(item.values())
def start():
"""爬蟲開始"""
low_score = int(input("輸入要爬取的最低分(以5為單位),最高分默認是加10>"))
high_score = low_score + 10
movie_type_list = get_movie_type()
for movie_type in movie_type_list:
print("{}爬取中...".format(movie_type[0]))
get_movie(movie_type, low_score, high_score)
if __name__ == '__main__':
start()
# 測驗代碼:
# content = parse_url(type_url)
# # 由于有iframe 所以不能使用xpath
# print(re.findall(r'<a href="/typerank\?type_name=(.*?)&type=(\d+)&interval_id=100:90&action=">.*?</a>',content))
#
#
# """
# <a href="/typerank?type_name=劇情&type=11&interval_id=100:90&action=">劇情</a>
#
# r'<a href="/typerank\?type_name=(.*?)&type=(\d+)&interval_id=100:90&action=">.*?</a>'
# """
#
# response = requests.get(url=movie_url,headers=headers)
# content = response.json()
# print(content)
五、保存完成結果



美好的日子總是短暫的,雖然還想繼續與大家暢談,但是本篇博文到此已經結束了,如果還嫌不夠過癮,不用擔心,我們下篇見!

??好書不厭讀百回,熟讀課思子自知,而我想要成為全場最靚的仔,就必須堅持通過學習來獲取更多知識,用知識改變命運,用博客見證成長,用行動證明我在努力,
??如果我的博客對你有幫助、如果你喜歡我的博客內容,請“點贊” “評論”“收藏”一鍵三連哦!聽說點贊的人運氣不會太差,每一天都會元氣滿滿呦!如果實在要白嫖的話,那祝你開心每一天,歡迎常來我博客看看,
??碼字不易,大家的支持就是我堅持下去的動力,點贊后不要忘了關注我哦!


轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/198884.html
標籤:其他

