Python爬虫——scrapy_crawlspider读书网

创建crawlspider爬虫文件:

base 复制代码
scrapy genspider -t crawl 爬虫文件名 爬取的域名

scrapy genspider -t crawl read https://www.dushu.com/book/1206.html

LinkExtractor 链接提取器通过它,Spider可以知道从爬取的页面中提取出哪些链接,提取出的链接会自动生成Request请求对象

python 复制代码
class ReadSpider(CrawlSpider):
    name = "read"
    allowed_domains = ["www.dushu.com"]
    start_urls = ["https://www.dushu.com/book/1206_1.html"]
	# LinkExtractor 链接提取器通过它,Spider可以知道从爬取的页面中提取出哪些链接。提取出的链接会自动生成Request请求对象
    rules = (Rule(LinkExtractor(allow=r"/book/1206_\d+\.html"), callback="parse_item", follow=False),)

    def parse_item(self, response):
        name_list = response.xpath('//div[@class="book-info"]//img/@alt')
        src_list = response.xpath('//div[@class="book-info"]//img/@data-original')


        for i in range(len(name_list)):
            name = name_list[i].extract()
            src = src_list[i].extract()

            book = ScarpyReadbook41Item(name=name, src=src)
            yield book

开启管道、

写入文件

python 复制代码
class ScarpyReadbook41Pipeline:
    def open_spider(self, spider):
        self.fp = open('books.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        self.fp.write(str(item))
        return item

    def close_spider(self, spider):
        self.fp.close()

运行之后发现没有第一页数据

需要在start_urls里加上_1,不然不会读取第一页数据

python 复制代码
start_urls = ["https://www.dushu.com/book/1206_1.html"]
相关推荐
wuyk55532 分钟前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
kyle~6 小时前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享7 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
梯度下降者8 小时前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信
MSTcheng.8 小时前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
the局外人9 小时前
Python 实战检索优化:BM25、向量与重排
数据库·后端·python
__underline__9 小时前
冷门Python知识点006篇:Python 类体里的名字,能被"凭空造出来"
后端·python
用户03321266636710 小时前
使用 Python 轻松移除 Excel 文档中的重复行
python·excel
LiaoWL12310 小时前
从零搭一个 RAG 知识库(二):换上语义 Embedding——BGE 实测与阈值重校准
python·大模型·numpy·embedding·向量检索·rag
Dmz丶10 小时前
前端转 AI 100 天 Day 48:向量数据库——100 万向量的毫秒级检索
python