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"]
相关推荐
Python私教4 分钟前
Python国产新 ORM 框架 fastzdp_sqlmodel 快速入门教程
java·数据库·python
Python私教4 分钟前
Python ORM 框架 SQLModel 快速入门教程
android·java·python
weixin_4193497921 分钟前
Python pdf转换为html
python·pdf
吉小雨32 分钟前
PyTorch经典模型
人工智能·pytorch·python
可愛小吉43 分钟前
Python 课程10-单元测试
开发语言·python·单元测试·tdd·unittest
student.J1 小时前
傅里叶变换
python·算法·傅里叶
Freak嵌入式2 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
java·开发语言·数据结构·python·接口·抽象基类
crownyouyou2 小时前
最简单的一文安装Pytorch+CUDA
人工智能·pytorch·python
鸽芷咕2 小时前
【Python报错已解决】libpng warning: iccp: known incorrect sRGB profile
开发语言·python·机器学习·bug
WenGyyyL2 小时前
变脸大师:基于OpenCV与Dlib的人脸换脸技术实现
人工智能·python·opencv