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"]
相关推荐
u***32434 小时前
使用python进行PostgreSQL 数据库连接
数据库·python·postgresql
ycydynq5 小时前
自动化验证码实现
爬虫·自动化
青瓷程序设计7 小时前
动物识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
tobebetter95277 小时前
How to manage python versions on windows
开发语言·windows·python
F_D_Z7 小时前
数据集相关类代码回顾理解 | sns.distplot\%matplotlib inline\sns.scatterplot
python·深度学习·matplotlib
daidaidaiyu8 小时前
一文入门 LangGraph 开发
python·ai
不知更鸟9 小时前
前端报错:快速解决Django接口404问题
前端·python·django
4***72139 小时前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
梁正雄9 小时前
1、python基础语法
开发语言·python
ituff10 小时前
微软认证考试又免费了
后端·python·flask