爬虫初探:豆瓣书籍信息爬取

给定需求:利用Python爬虫爬取豆瓣网编程类的前n页书籍的‘书籍名称’、‘著作者/译者/出版社/出版日期/价格’和‘评分’,并将这三组数据信息分列保存至CSV文件中。

问题分析:分三步骤实现获取网页内容、提取信息到数据结构中和保存书籍信息。

(1)步骤1:从网络上获取编程书籍网页内容;

(2)步骤2:提取网页内容中的书籍信息‘书籍名称’、‘著作者/译者/出版社/出版日期/价格’和‘评分’到数据结构中;

(3)步骤3:利用数据结构将书籍信息保存至CSV文件中。

代码实现:

import requests

from bs4 import BeautifulSoup

import csv

 

def getHTMLText(url):

    try:

        kv = {"user-agent":"Mozilla/5.0"}

        r = requests.get(url,headers=kv)

        r.raise_for_status()

        r.encoding = r.apparent_encoding

        return r.text

    except:

        print("产生异常")

 

def fillBookInfo(blist,html):

    soup = BeautifulSoup(html,"html.parser")

    for i in soup.find_all('a'):

        if i.get('title') == None:

            pass

        else:

            blist[0].append(i.get('title'))

    for j in soup.find_all('div',class_="pub"):

        blist[1].append(j.string.replace('\n','').strip())

    for k in soup.find_all('span',class_="rating_nums"):

        blist[2].append(k.string)

 

def saveBookInfo(blist,num):

    with open('E:\Spider\BookInfo.csv','w',newline="",encoding='gb18030') as f:

        f_csv = csv.writer(f)       

        f_csv.writerow(["书籍名称","著作者/译者/出版社/出版日期/价格","评分"])

        for i in range(num):

            f_csv.writerow([blist[0][i],blist[1][i],blist[2][i]])

 

def main():

    blist =[[],[],[]]

    depth = 5

    for p in range(depth):

        url = "https://book.douban.com/tag/%E7%BC%96%E7%A8%8B?start="+str(p*20)+"&type=T"

        html = getHTMLText(url)

        fillBookInfo(blist,html)

    saveBookInfo(blist,depth*20)

 

main()
posted @ 2023-04-09 14:59  数字质检官  阅读(348)  评论(0)    收藏  举报