会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132358个问题
Python 全系列/第十五阶段:Python 爬虫开发/爬虫反反爬- 346楼
Python 全系列/第十五阶段:Python 爬虫开发/爬虫数据存储 348楼
Python 全系列/第十五阶段:Python 爬虫开发/移动端爬虫开发- 349楼

import scrapy

class XiaoshuoSpider(scrapy.Spider):
    name = "xiaoshuo"
    allowed_domains = ["zhhbqg.com"]
    start_urls = ["https://www.bqgui.cc/book/108732/1.html"]

    def parse(self, response):
        # 章节名称
        title = response.xpath('//h1/text()').extract_first()
        # 章节内容
        content = response.xpath('//div[@id="chaptercontent"]/text()').extract()
        # 下一章链接
        next_btn = response.xpath('//a[@id="pb_next"]/@href').get()

        yield {
            "title": title,
            "content": content
        }
        yield scrapy.Request('https://www.bqgui.cc'+next_btn, callback=self.parse)
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

class Scrapy06Pipeline:
    def open_spider(self, spider):
        self.file = open('xiaoshuo.txt', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        self.file.write(item['title'] + '\n')
        self.file.write(''.join(item['content']) + '\n\n\n')
        return item

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

下一章功能没有实现,只能爬取第一章,这是为什么呢?

image.png

Python 全系列/第十五阶段:Python 爬虫开发/scrapy框架使用 351楼

我准备爬取https://m.lread.net的一本小说,这小说有时候 一个章节分了两页html。我如何将第二页的内容与前一页内容合并,保存到csv文件里?

image.png

#pipelines.py
import csv
class RuanyunPipeline(object):
    def __init__(self):
        self.filename= open('douluodalu.csv','w',newline="",encoding='utf-8')
        self.writer=csv.writer(self.filename)
        self.writer.writerow(['title','url_next','content'])
    def process_item(self, item, spider):
        if '-' not in item['url_now']:
            self.writer.writerow([item['title'],item['url_now'],item['content']])
        else :
            self.writer.writerow([item['title'],item['url_now'],item['content']])
        return item
    def close_spider(self,spider):
        if self.filename:
            self.filename.close()

ruanyun.zip


Python 全系列/第十五阶段:Python 爬虫开发/移动端爬虫开发- 352楼

image.png

Python 全系列/第十五阶段:Python 爬虫开发/Python爬虫基础与应用 353楼
Python 全系列/第十五阶段:Python 爬虫开发/爬虫反反爬- 356楼
Python 全系列/第十五阶段:Python 爬虫开发/爬虫反反爬 358楼
Python 全系列/第十五阶段:Python 爬虫开发/Python爬虫基础与应用 359楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637