python3爬蟲-6.使用requests和BeautifulSoup爬取豆瓣Top250電影


初次探查

這次使用上次說的BeautifulSoup + Reuqests進行爬取豆瓣TOP250電影

將爬取到的內容存放到 excel

打開目標網站https://movie.douban.com/top250?start=0&filter=

每次點擊下一頁,start的值會加25,一共十頁,最大225

image-20210823173051884

接下來我們來看下我們要的主要信息

  • 電影名稱

  • 電影圖片

  • 電影排名

  • 電影評分

  • 電影作者

  • 電影簡介

image-20210823173529672

步驟

主要思路:

​ 請求豆瓣的鏈接獲取網頁源代碼

​ 然后使用 BeatifulSoup 拿到我們要的內容

​ 最后就把數據存儲到 excel 文件中

def main(page):
    url="https://movie.douban.com/top250?start="+str(page*25)+"&filter="#獲取鏈接
    html=request_douban(url)#獲取html
    soup=BeautifulSoup(html,"lxml")#處理html,獲取所需信息
    save_to_excel(soup)#處理並保存所需信息

處理url

#請求豆瓣電影
def request_douban(url):
    try:
        response=requests.get(url)
        if response.status_code==200:
            return response.text
    except requests.RequestException:
        return None

獲取html

soup=BeautifulSoup(html,"lxml")

處理html獲取所需信息

信息都在grid_view類里

image-20210824113659769

def save_to_excel(soup):
    list = soup.find(class_="grid_view").find_all("li")#獲取關鍵信息部分的html
    for item in list:
        item_name = item.find(class_="title").string#獲取名稱
        item_img = item.find("a").find("img").get("src")#獲取圖片
        item_index = item.find(class_="").string#獲取排名
        item_score = item.find(class_="rating_num").string#獲取評分
        if item.find(class_='inq') is not None:			#獲取評價
            item_quote = item.find(class_="inq").string
        else:
            item_quote=""
        item_author = item.find(class_="bd").find(class_="").text #獲取導演,演員信息
        print("爬取電影:" + item_name + "|" + item_score + "|" + item_quote)#打印獲取詳情
        global n
        sheet.write(n,0,item_name)
        sheet.write(n, 1, item_img)
        sheet.write(n, 2, item_index)
        sheet.write(n, 3, item_score)
        sheet.write(n, 4, item_author)
        sheet.write(n, 5, item_quote)
        n+=1
    return None

主執行函數,寫入excel文件

寫入excel文件需要用到xlwt庫

Python xlwt 用法說明_

if __name__=="__main__":
    n = 1
    book = xlwt.Workbook()# 創建一個工作薄,可以在里面設置參數比如encoding="utf-8" 
    sheet = book.add_sheet("豆瓣電影TOP250", cell_overwrite_ok=True) #創建一個工作表,名稱為"豆瓣電影TOP250";允許覆蓋寫入
   
   # 寫入第i行第j列的單元格
    sheet.write(0, 0, "名稱")
    sheet.write(0, 1, "圖片")
    sheet.write(0, 2, "排名")
    sheet.write(0, 3, "評分")
    sheet.write(0, 4, "作者")
    sheet.write(0, 5, "簡介")
    for i in range(0,10):
        main(i)
    book.save(u"豆瓣電影TOP250.xls")#xlsx.save( path )保存文件
    print("爬取完成")

遇到的問題

1.如果打開了系統代理,運行的時候可能會報錯

image-20210824114953048

2.book.save()保存的是xls文件,因此命名的文件格式也應該是xls,不然會顯示格式損壞,無法打開文件

3.爬取的有些部分值可能是空的,比如這里的item_quote有時為空,所以要注意加以判斷

4.寫入的內容必須與工作簿的編碼一致,否則在保存的時候會報錯,比如,設置編碼為utf-8,那么所有寫入的內容都必須是utf-8的編碼

完整代碼

from bs4 import BeautifulSoup
import requests
import xlwt

def main(page):
    url="https://movie.douban.com/top250?start="+str(page*25)+"&filter="
    html=request_douban(url)
    soup=BeautifulSoup(html,"lxml")
    #solve_html(soup)
    save_to_excel(soup)
#請求豆瓣電影
def request_douban(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/88.0.4324.146 Safari/537.36',
    }

    try:
        response=requests.get(url=url,headers=headers)
        if response.status_code==200:
            return response.text
    except requests.RequestException:
        return None



def save_to_excel(soup):
    list = soup.find(class_="grid_view").find_all("li")
    for item in list:
        item_name = item.find(class_="title").string
        item_img = item.find("a").find("img").get("src")
        item_index = item.find(class_="").string
        item_score = item.find(class_="rating_num").string
        if item.find(class_='inq') is not None:
            item_quote = item.find(class_="inq").string
        else:
            item_quote=""
        item_author = item.find(class_="bd").find(class_="").text
        print("爬取電影:" + item_name + "|" + item_score + "|" + item_quote)
        global n
        sheet.write(n,0,item_name)
        sheet.write(n, 1, item_img)
        sheet.write(n, 2, item_index)
        sheet.write(n, 3, item_score)
        sheet.write(n, 4, item_author)
        sheet.write(n, 5, item_quote)
        n+=1
    return None


if __name__=="__main__":
    n = 1
    book = xlwt.Workbook()
    sheet = book.add_sheet("豆瓣電影TOP250", cell_overwrite_ok=True)
    sheet.write(0, 0, "名稱")
    sheet.write(0, 1, "圖片")
    sheet.write(0, 2, "排名")
    sheet.write(0, 3, "評分")
    sheet.write(0, 4, "作者")
    sheet.write(0, 5, "簡介")
    for i in range(0,10):
        main(i)
    book.save(u"豆瓣電影TOP250.xls")
    print("爬取完成")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM