Python小作业
题目:
从京东爬取2019年 “计算与互联网”的图书销量榜,包括图书的"书名", “作者”, “出版社”, “定价”, “京东价”, “好评率”,存入csv文件中。
爬取结果:
链接:https://pan.baidu.com/s/19PcHiFzIk0efVBXTgNoupw
提取码:vmua
注:网页结构及数据接口地址有可能发生变化,因此不能保证其时效性。
分析
爬取网页https://book.jd.com/booktop/0-0-0.html?category=3287-0-0-0-5-1
需要安装的库:
import requests
from bs4 import BeautifulSoup
import random
import re
import json
from selenium import webdriver
import time
import csv
运行selenium还需下载相应浏览器的驱动,并且拷贝到python的安装目录。
首先分析url中最后以为数字代表页数,由此可以通过拼接url的方式得到2019年的共5页的url。
url = "https://book.jd.com/booktop/0-0-0.html?category=3287-0-0-0-10005-"
count = 0
for i in range(1, 6):
r = requests.get(url + str(i), headers=headers)
r.encoding = "GBK"
soup = BeautifulSoup(r.text, "html.parser")
li = soup.find('ul', class_="clearfix").find_all('li')
使用bs4库对返回的页面进行解析,获取“作者”和“出版社”并保存在变量中。
for e in li:
count += 1
detail = e.find('div', class_="p-detail")
href = "https:" + detail.find('a')['href'] # 二级链接
dl = detail.find_all('dl')
author = dl[0].find('dd').text.replace(' ', '').replace("\n", ' ').replace("著", "著 ") # 作者
press = dl[1].find('a').string # 出版社
因书名在当前页面显示不完整,所以在商品详情页面获取。
new_soup