新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

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

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

发展壮大离不开广大客户长期以来的信赖与支持,我们将始终秉承“诚信为本、服务至上”的服务理念,坚持“二合一”的优良服务模式,真诚服务每家企业,认真做好每个细节,不断完善自我,成就企业,实现共赢。行业涉及混凝土搅拌机等,在成都网站建设全网整合营销推广、WAP手机网站、VI设计、软件开发等项目上具有丰富的设计经验。

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

(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='gb') 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()

本文题目:爬虫初探:豆瓣书籍信息爬取
网页网址:http://www.wjwzjz.com/article/dsojdjd.html
在线咨询
服务热线
服务热线:028-86922220
TOP