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"]
相关推荐
心情好的小球藻28 分钟前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
都叫我大帅哥29 分钟前
LangChain加载HTML内容全攻略:从入门到精通
python·langchain
惜.己40 分钟前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
都叫我大帅哥2 小时前
Python的Optional:让你的代码优雅处理“空值”危机
python
曾几何时`4 小时前
基于python和neo4j构建知识图谱医药问答系统
python·知识图谱·neo4j
写写闲篇儿6 小时前
Python+MongoDB高效开发组合
linux·python·mongodb
杭州杭州杭州7 小时前
Python笔记
开发语言·笔记·python
路人蛃9 小时前
通过国内扣子(Coze)搭建智能体并接入discord机器人
人工智能·python·ubuntu·ai·aigc·个人开发
qiqiqi(^_×)9 小时前
卡在“pycharm正在创建帮助程序目录”
ide·python·pycharm
Ching·10 小时前
esp32使用ESP-IDF在Linux下的升级步骤,和遇到的坑Traceback (most recent call last):,及解决
linux·python·esp32·esp_idf升级