高级深入--day38

news/2024/7/19 8:46:45 标签: 1024程序员节, python, 爬虫, scrapy

阳光热线问政平台

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

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

items.py

python">import scrapy

class DongguanItem(scrapy.Item):
    # 每个帖子的标题
    title = scrapy.Field()
    # 每个帖子的编号
    number = scrapy.Field()
    # 每个帖子的文字内容
    content = scrapy.Field()
    # 每个帖子的url
    url = scrapy.Field()

spiders/sunwz.py

Spider 版本
python"># -*- coding: utf-8 -*-

import scrapy
from dongguan.items import DongguanItem

class SunSpider(CrawlSpider):
    name = 'sun'
    allowed_domains = ['wz.sun0769.com']
    url = 'http://wz.sun0769.com/index.php/question/questionType?type=4&page='
    offset = 0
    start_urls = [url + str(offset)]

    def parse(self, response):
        # 取出每个页面里帖子链接列表
        links = response.xpath("//div[@class='greyframe']/table//td/a[@class='news14']/@href").extract()
        # 迭代发送每个帖子的请求,调用parse_item方法处理
        for link in links:
            yield scrapy.Request(link, callback = self.parse_item)
        # 设置页码终止条件,并且每次发送新的页面请求调用parse方法处理
        if self.offset <= 71130:
            self.offset += 30
            yield scrapy.Request(self.url + str(self.offset), callback = self.parse)

    # 处理每个帖子里
    def parse_item(self, response):
        item = DongguanItem()
        # 标题
        item['title'] = response.xpath('//div[contains(@class, "pagecenter p3")]//strong/text()').extract()[0]

        # 编号
        item['number'] = item['title'].split(' ')[-1].split(":")[-1]

        # 文字内容,默认先取出有图片情况下的文字内容列表
        content = response.xpath('//div[@class="contentext"]/text()').extract()
        # 如果没有内容,则取出没有图片情况下的文字内容列表
        if len(content) == 0:
            content = response.xpath('//div[@class="c1 text14_2"]/text()').extract()
            # content为列表,通过join方法拼接为字符串,并去除首尾空格
            item['content'] = "".join(content).strip()
        else:
            item['content'] = "".join(content).strip()

        # 链接
        item['url'] = response.url

        yield item
CrawlSpider 版本
python">
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from dongguan.items import DongguanItem
import time


class SunSpider(CrawlSpider):
    name = 'sun'
    allowed_domains = ['wz.sun0769.com']
    start_urls = ['http://wz.sun0769.com/index.php/question/questionType?type=4&page=']

    # 每一页的匹配规则
    pagelink = LinkExtractor(allow=('type=4'))
    # 每个帖子的匹配规则
    contentlink = LinkExtractor(allow=r'/html/question/\d+/\d+.shtml')

    rules = [
        # 本案例为特殊情况,需要调用deal_links方法处理每个页面里的链接
        Rule(pagelink, process_links = "deal_links", follow = True),
        Rule(contentlink, callback = 'parse_item')
    ]

    # 需要重新处理每个页面里的链接,将链接里的‘Type&type=4?page=xxx’替换为‘Type?type=4&page=xxx’(或者是Type&page=xxx?type=4’替换为‘Type?page=xxx&type=4’),否则无法发送这个链接
    def deal_links(self, links):
        for link in links:
            link.url = link.url.replace("?","&").replace("Type&", "Type?")
            print link.url
        return links


    def parse_item(self, response):
        print response.url
        item = DongguanItem()
        # 标题
        item['title'] = response.xpath('//div[contains(@class, "pagecenter p3")]//strong/text()').extract()[0]

        # 编号
        item['number'] = item['title'].split(' ')[-1].split(":")[-1]

        # 文字内容,默认先取出有图片情况下的文字内容列表
        content = response.xpath('//div[@class="contentext"]/text()').extract()
        # 如果没有内容,则取出没有图片情况下的文字内容列表
        if len(content) == 0:
            content = response.xpath('//div[@class="c1 text14_2"]/text()').extract()
            # content为列表,通过join方法拼接为字符串,并去除首尾空格
            item['content'] = "".join(content).strip()
        else:
            item['content'] = "".join(content).strip()

        # 链接
        item['url'] = response.url

        yield item
pipelines.py
python"># -*- coding: utf-8 -*-

# 文件处理类库,可以指定编码格式
import codecs
import json

class JsonWriterPipeline(object):

    def __init__(self):
        # 创建一个只写文件,指定文本编码格式为utf-8
        self.filename = codecs.open('sunwz.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        content = json.dumps(dict(item), ensure_ascii=False) + "\n"
        self.filename.write(content)
        return item

    def spider_closed(self, spider):
        self.file.close()
settings.py
python">ITEM_PIPELINES = {
    'dongguan.pipelines.DongguanPipeline': 300,
}

# 日志文件名和处理等级
LOG_FILE = "dg.log"
LOG_LEVEL = "DEBUG"
在项目根目录下新建main.py文件,用于调试
python">from scrapy import cmdline
cmdline.execute('scrapy crawl sunwz'.split())
执行程序
python">py2 main.py

http://www.niftyadmin.cn/n/5119447.html

相关文章

【大数据】Hadoop

文章目录 概述Hadoop组成HDFSMapReduce写MapReduce程序&#xff08;Hadoop streaming&#xff09; YARNHadoop 启动 工作方式Hadoop的主从工作方式Hadoop的守护进程 运行模式本地运行模式伪分布式运行模式完全分布式运行模式 Hadoop高可用的解决方案ZooKeeper quorumZKFC 环境搭…

记录nvm use node.js版本失败,出现报错: exit status 1: ��û���㹻��Ȩ��ִ�д˲�����

使用管理员权限运行cmd&#xff0c;再使用nvm use node.js版本号 参考&#xff1a; nvm use (node版本号)时报错&#xff1a; exit status 1: &#xfffd;&#xfffd;&#xfffd;&#xfffd;&#xfffd;㹻&#xfffd;&#xfffd;Ȩ&#xfffd;&#xfffd;ִ&#xf…

互联网Java工程师面试题·Spring篇·第四弹

目录 6、AOP 6.1、什么是 AOP&#xff1f; 6.2、什么是 Aspect&#xff1f; 6.3、什么是切点&#xff08;JoinPoint&#xff09; 6.4、什么是通知&#xff08;Advice&#xff09;&#xff1f; 6.5、有哪些类型的通知&#xff08;Advice&#xff09;&#xff1f; 6.6、指出…

fastjson对象序列化的问题

今天偶然遇到一个fastjson将字符串反序列化为一个对象的时候的问题&#xff0c;就是简单的通过com.alibaba.fastjson.JSON将对象转为字符串&#xff0c;然后再从字符串转换为原类型的对象。 涉及的代码也非常简单 package cn.edu.sgu.www.mhxysy.service.role.impl;import cn…

13.4web自动化测试(Selenium3+Java)

一.定义 用来做web自动化测试的框架. 二.特点 1.支持各种浏览器. 2.支持各种平台(操作系统). 3.支持各种编程语言. 4.有丰富的api. 三.工作原理 四.搭环境 1.对照Chrome浏览器版本号,下载ChromeDriver,配置环境变量,我直接把.exe文件放在了jdk安装路径的bin文件夹下了(j…

[100天算法】-不同路径(day 37)

题目描述 一个机器人位于一个 m x n 网格的左上角 &#xff08;起始点在下图中标记为“Start” &#xff09;。机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角&#xff08;在下图中标记为“Finish”&#xff09;。问总共有多少条不同的路径&#xff1f;例如…

使用create-vue创建项目

认识create-vue create-vue是Vue官方新的脚手架工具&#xff0c;底层切换到了vite&#xff08;下一代构建工具&#xff09;&#xff0c;为开发提供极速响应。 使用create-vue创建项目 1.前提环境条件 已安装16.0或更高版本的Node.js node -v 2.创建一个Vue应用 npm init…

vue项目中隐藏右侧滑动栏,使用鼠标滚轮滑动

直接加一个样式&#xff0c;就什么也不用管了 ::-webkit-scrollbar {display: none; }