赞
踩
保存起点中文网
月票榜的排名、书名、作者、链接到 excel 中。
HTML
文档内容,确定要抽取标记的位置。起点月票榜的小说名称在<div class=’book-mid-info’>
下的<h4>
下的 <a>
标记中,作者在<p class=’author’>
下的第一个<a>
中。# 使用xPath爬取起点小说月票榜书名和作者 import requests, openpyxl from lxml import etree # 获取HTML源码 def getHtml(url): try: # 用户代理 headers = {'User_Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'} # 获取请求对象 r = requests.get(url, timeout=5, headers=headers) r.raise_for_status() # 返回页面内容 return r.text except Exception as e: print(e.__traceback__)
使用XPath解析,相关语法学习请参考 爬虫进阶- XPath应用
# 解析内容
def getInfo(text):
# 获取xpath解析对象
e = etree.HTML(text)
# 获取所有书的名称
names = e.xpath('//div[@class="book-mid-info"]/h4/a/text()')
# 获取所有作者
authors = e.xpath('//p[@class="author"]/a[1]/text()')
# 获取链接
links = e.xpath('//div[@class="book-mid-info"]/h4/a/@href')
# 合并为元组返回
return zip(names, authors, links)
输出结果到excel表格中
# 保存数据
def save(i, data, ws):
index = (i-1)*20+1
for name, author, link in data:
ws.append([index, name, author, link])
index += 1
由于页面共有5页,分析得每页20个小说,共100部。
网址:https://www.qidian.com/rank/yuepiao?page=2
因此代码稍作修改,爬取全部页面内容。
# 使用xPath爬取起点小说月票榜书名和作者 import requests, openpyxl from lxml import etree # 获取HTML源码 def getHtml(url): try: # 用户代理 headers = {'User_Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'} # 获取请求对象 r = requests.get(url, timeout=5, headers=headers) r.raise_for_status() # 返回页面内容 return r.text except Exception as e: print(e.__traceback__) # 解析内容 def getInfo(text): # 获取xpath解析对象 e = etree.HTML(text) # 获取所有书的名称 names = e.xpath('//div[@class="book-mid-info"]/h4/a/text()') # 获取所有作者 authors = e.xpath('//p[@class="author"]/a[1]/text()') # 获取链接 links = e.xpath('//div[@class="book-mid-info"]/h4/a/@href') return zip(names, authors, links) # 保存数据 def save(i, data, ws): # 排名信息 index = (i-1)*20+1 for name, author, link in data: ws.append([index, name, author, link]) index += 1 if __name__=='__main__': # 创建excel文件 # 获取工作簿 wb = openpyxl.Workbook() # 获取工作表 ws = wb.active # 设置工作表名 ws.title = '起点中文网月票榜' # 设置表头 ws.append(['排名', '名称', '作者', '链接']) # url = 'https://www.qidian.com/rank/yuepiao' # https://www.qidian.com/rank/yuepiao?page=1 # 共5页 for i in range(1, 6): url = 'https://www.qidian.com/rank/yuepiao?page='+str(i) text = getHtml(url) data = getInfo(text) save(i, data, ws) # 保存 wb.save('qidian.xlsx')
如果需要其他作品信息,方法类似。
比如,获取作品简介,可以使用XPath解析:
//p[@class="intro"/text()]
感谢努力,一起加油!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。