起点小说:(空山老师授课所记得笔记)(VIP暂不能爬取)
小说名 + 章名 + 文章内容
文件夹 文章内容 《--》
1、请求网站拿到数据,抽取小说名创建文件夹,抽取小说链接
2、请求小说拿到数据,抽取章名,抽取文章链接
3、请求文章拿到抽取文章内容,创建文件保存到相应文件夹
---
设置模式:----面向对象
class Spidef(object)
request.get(获取网址)---HTML源代码
import requests
from lxml import etree
import os
# 设计模式 -- 面向对象
class Spider(object):
def start_request(self):
# 1. 请求网站拿到数据,抽取小说名创建文件夹,抽取小说链接
response = requests.get("https://www.qidian.com/all")
html = etree.HTML(response.text) # 结构化
Bigsrc_list = html.xpath('//div[@class="book-mid-info"]/h4/a/@href')
Bigtit_list = html.xpath('//div[@class="book-mid-info"]/h4/a/text()')
for Bigsrc, Bigtit in zip(Bigsrc_list, Bigtit_list):
if os.path.exists(Bigtit) == False:
os.mkdir(Bigtit)
self.file_data(Bigsrc, Bigtit)
def file_data(self, Bigsrc, Bigtit):
# 2. 请求小说拿到数据,抽取章名,抽取文章链接
response = requests.get("https:" + Bigsrc)
html = etree.HTML(response.text) # 结构化
Litsrc_list = html.xpath('//ul[@class="cf"]/li/a/@href')
Littit_list = html.xpath('//ul[@class="cf"]/li/a/text()')
for Litsrc, Littit in zip(Litsrc_list, Littit_list):
self.finally_file(Litsrc, Littit, Bigtit)
def finally_file(self, Litsrc, Littit, Bigtit):
# 3. 请求文章拿到抽取文章内容,创建文件保存到相应文件夹
response = requests.get("https:" + Litsrc)
html = etree.HTML(response.text) # 结构化
# xpth是属于list数据类型,可以用"\n".join()将list(列表)转换为str(字符串)
content = "\n".join(html.xpath('//div[@class="read-content j_readContent"]/p/text()'))
file_name = Bigtit + "\\" + Littit + ".txt"
print("正在存储文件:" + file_name)
with open(file_name, "a", encoding="utf-8") as f:
f.write(content)
spider = Spider()
spider.start_request()