求助!如何爬取当当网畅销榜图书的折扣,就差这一个

import requests
from bs4 import BeautifulSoup
import re
import csv

headers = {‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3314.0 Safari/537.36 SE 2.X MetaSr 1.0’}

def getHTMLText(url):
try:
r = requests.get(url, headers=headers)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except Exception as e:
print(e)

def getBookInfo(html, lst):
soup = BeautifulSoup(html, ‘html.parser’)
tag_ul = soup.find(‘ul’, attrs={‘class’: ‘bang_list clearfix bang_list_mode’})
tag_li = tag_ul.find_all(‘li’)
for book in tag_li:
book_info = {}

    book_rank = book.find('div', attrs={'class': re.compile('list_num$')})

    book_name = book.find('div', attrs={'class': 'name'}).a

    book_comments = book.find('div', attrs={'class': 'star'}).a

    book_author = book.find_all('div', attrs={'class': 'publisher_info'})[0].a

    book_author_sup = book.find_all('div', attrs={'class': 'publisher_info'})[0]

    book_publish_date = book.find_all('div', attrs={'class': 'publisher_info'})[1].span

    book_publish_company = book.find_all('div', attrs={'class': 'publisher_info'})[1].a
    
    book_discount = book.find_all('div', attrs={'class': 'price_s'})

    
    book_price = book.find('div', attrs={'class': 'price'}).span

    book_info.update({'排名': book_rank.get_text()[:-1]})
    book_info.update({'书名': book_name.get_text()})
    book_info.update({'评论数': book_comments.get_text()[:-3]})
    book_info.update({'折扣': book_discount.get_text()})
    try:
        book_info.update({'作者': book_author.get_text()})
        
    except:
        book_info.update({'作者': book_author_sup.get_text()})
    book_info.update({'出版日期': book_publish_date.get_text()})
    book_info.update({'出版社': book_publish_company.get_text()})
    
    book_info.update({'售价': book_price.get_text()[-5:]})
    

    lst.append(book_info)

return lst

def saveCsvFile(path, lst, fieldnames):

with open(path, 'w', encoding='utf-8-sig', newline="") as file:
    dictWriter = csv.DictWriter(file, fieldnames)
    dictWriter.writeheader()
    dictWriter.writerows(lst)

def main():
book_list = []
fieldnames = [‘排名’, ‘书名’, ‘作者’, ‘评论数’, ‘出版日期’, ‘出版社’,‘折扣’,‘售价’]
path = ‘D:/astute/dangdangBookRank.csv’
url = ‘http://bang.dangdang.com/books/bestsellers/01.00.00.00.00.00-24hours-0-0-1-’

for page in range(1, 6):
    des_url = url + str(page)
    html = getHTMLText(des_url)
    book_list = getBookInfo(html, book_list)
    print('正在爬取第' + str(page) + '页......')

saveCsvFile(path, book_list, fieldnames)

main()在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值