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"]
相关推荐
用户25191624271131 分钟前
Python之语言特点
python
刘立军1 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机4 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机5 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i7 小时前
django中的FBV 和 CBV
python·django
c8i7 小时前
python中的闭包和装饰器
python
这里有鱼汤10 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩20 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在1 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP1 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python