• 高级深入--day38


    阳光热线问政平台

    http://wz.sun0769.com/index.php/question/questionType?type=4

    爬取投诉帖子的编号、帖子的url、帖子的标题,和帖子里的内容。

    items.py

    1. import scrapy
    2. class DongguanItem(scrapy.Item):
    3. # 每个帖子的标题
    4. title = scrapy.Field()
    5. # 每个帖子的编号
    6. number = scrapy.Field()
    7. # 每个帖子的文字内容
    8. content = scrapy.Field()
    9. # 每个帖子的url
    10. url = scrapy.Field()

    spiders/sunwz.py

    Spider 版本
    1. # -*- coding: utf-8 -*-
    2. import scrapy
    3. from dongguan.items import DongguanItem
    4. class SunSpider(CrawlSpider):
    5. name = 'sun'
    6. allowed_domains = ['wz.sun0769.com']
    7. url = 'http://wz.sun0769.com/index.php/question/questionType?type=4&page='
    8. offset = 0
    9. start_urls = [url + str(offset)]
    10. def parse(self, response):
    11. # 取出每个页面里帖子链接列表
    12. links = response.xpath("//div[@class='greyframe']/table//td/a[@class='news14']/@href").extract()
    13. # 迭代发送每个帖子的请求,调用parse_item方法处理
    14. for link in links:
    15. yield scrapy.Request(link, callback = self.parse_item)
    16. # 设置页码终止条件,并且每次发送新的页面请求调用parse方法处理
    17. if self.offset <= 71130:
    18. self.offset += 30
    19. yield scrapy.Request(self.url + str(self.offset), callback = self.parse)
    20. # 处理每个帖子里
    21. def parse_item(self, response):
    22. item = DongguanItem()
    23. # 标题
    24. item['title'] = response.xpath('//div[contains(@class, "pagecenter p3")]//strong/text()').extract()[0]
    25. # 编号
    26. item['number'] = item['title'].split(' ')[-1].split(":")[-1]
    27. # 文字内容,默认先取出有图片情况下的文字内容列表
    28. content = response.xpath('//div[@class="contentext"]/text()').extract()
    29. # 如果没有内容,则取出没有图片情况下的文字内容列表
    30. if len(content) == 0:
    31. content = response.xpath('//div[@class="c1 text14_2"]/text()').extract()
    32. # content为列表,通过join方法拼接为字符串,并去除首尾空格
    33. item['content'] = "".join(content).strip()
    34. else:
    35. item['content'] = "".join(content).strip()
    36. # 链接
    37. item['url'] = response.url
    38. yield item
    CrawlSpider 版本
    1. # -*- coding: utf-8 -*-
    2. import scrapy
    3. from scrapy.linkextractors import LinkExtractor
    4. from scrapy.spiders import CrawlSpider, Rule
    5. from dongguan.items import DongguanItem
    6. import time
    7. class SunSpider(CrawlSpider):
    8. name = 'sun'
    9. allowed_domains = ['wz.sun0769.com']
    10. start_urls = ['http://wz.sun0769.com/index.php/question/questionType?type=4&page=']
    11. # 每一页的匹配规则
    12. pagelink = LinkExtractor(allow=('type=4'))
    13. # 每个帖子的匹配规则
    14. contentlink = LinkExtractor(allow=r'/html/question/\d+/\d+.shtml')
    15. rules = [
    16. # 本案例为特殊情况,需要调用deal_links方法处理每个页面里的链接
    17. Rule(pagelink, process_links = "deal_links", follow = True),
    18. Rule(contentlink, callback = 'parse_item')
    19. ]
    20. # 需要重新处理每个页面里的链接,将链接里的‘Type&type=4?page=xxx’替换为‘Type?type=4&page=xxx’(或者是Type&page=xxx?type=4’替换为‘Type?page=xxx&type=4’),否则无法发送这个链接
    21. def deal_links(self, links):
    22. for link in links:
    23. link.url = link.url.replace("?","&").replace("Type&", "Type?")
    24. print link.url
    25. return links
    26. def parse_item(self, response):
    27. print response.url
    28. item = DongguanItem()
    29. # 标题
    30. item['title'] = response.xpath('//div[contains(@class, "pagecenter p3")]//strong/text()').extract()[0]
    31. # 编号
    32. item['number'] = item['title'].split(' ')[-1].split(":")[-1]
    33. # 文字内容,默认先取出有图片情况下的文字内容列表
    34. content = response.xpath('//div[@class="contentext"]/text()').extract()
    35. # 如果没有内容,则取出没有图片情况下的文字内容列表
    36. if len(content) == 0:
    37. content = response.xpath('//div[@class="c1 text14_2"]/text()').extract()
    38. # content为列表,通过join方法拼接为字符串,并去除首尾空格
    39. item['content'] = "".join(content).strip()
    40. else:
    41. item['content'] = "".join(content).strip()
    42. # 链接
    43. item['url'] = response.url
    44. yield item
    pipelines.py
    1. # -*- coding: utf-8 -*-
    2. # 文件处理类库,可以指定编码格式
    3. import codecs
    4. import json
    5. class JsonWriterPipeline(object):
    6. def __init__(self):
    7. # 创建一个只写文件,指定文本编码格式为utf-8
    8. self.filename = codecs.open('sunwz.json', 'w', encoding='utf-8')
    9. def process_item(self, item, spider):
    10. content = json.dumps(dict(item), ensure_ascii=False) + "\n"
    11. self.filename.write(content)
    12. return item
    13. def spider_closed(self, spider):
    14. self.file.close()
    settings.py
    1. ITEM_PIPELINES = {
    2. 'dongguan.pipelines.DongguanPipeline': 300,
    3. }
    4. # 日志文件名和处理等级
    5. LOG_FILE = "dg.log"
    6. LOG_LEVEL = "DEBUG"
    在项目根目录下新建main.py文件,用于调试
    1. from scrapy import cmdline
    2. cmdline.execute('scrapy crawl sunwz'.split())
    执行程序
    py2 main.py
  • 相关阅读:
    javaScript(js)手写原生任务定时器源码
    内容+货架“攻防一体”,京东能否上演“后来居上”?
    关于lua源代码中的EXTRA_STACK宏
    Qt实现一个简易截图工具(支持缩放、移动、保存、复制到粘贴板)
    9个Excel小技巧,提高你的数据分析效率
    【原创】java+springboot+mysql日程管理系统设计与实现
    Linux下的一些工具
    vue网页缓存页面与不缓存页面处理
    【Linux环境安装教程】
    uniapp实现点击图片预览放大,长按下载图片
  • 原文地址:https://blog.csdn.net/qq_41813416/article/details/134022363