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()