获取欧洲时报中国板块前新闻数据-scrapy

news2024/9/22 21:31:34

这里写目录标题

  • 1.创建项目文件
  • 二.爬虫文件编写
  • 三.管道存储
  • 四.settings文件

1.创建项目文件

创建scrapy项目的命令:scrapy startproject <项目名字>
示例:
scrapy startproject myspider

在这里插入图片描述

 scrapy genspider <爬虫名字> <允许爬取的域名>
cd myspider
scrapy genspider itcast itcast.cn

二.爬虫文件编写

import time
import scrapy
from ..items import ChinanewsItem
s=1
class NewsSpider(scrapy.Spider):
    name = 'news'
    allowed_domains = []
    start_urls = ['https://cms.offshoremedia.net/front/list/latest?pageNum=1&pageSize=15&siteId=694841922577108992&channelId=780811183157682176']

    def parse(self, response):
        #print(response)
        global s
        res=response.json()
        for i in res["info"]["list"]:

            try:
                newurl = i["contentStaticPage"]
                #print(newurl)
                yield scrapy.Request(url=newurl,callback=self.datas,cb_kwargs={'newurl': newurl},dont_filter=True)
            except Exception as e:
                print(f"Failed to process URL {i['contentStaticPage']}: {str(e)}")
        s=s+1
        if s<1000:
            print(s)
            url=f'https://cms.offshoremedia.net/front/list/latest?pageNum={str(s)}&pageSize=15&siteId=694841922577108992&channelId=780811183157682176'
            #print(url)
            yield scrapy.Request(url=url, callback=self.parse)
    def datas(self,response,newurl):
        print(response)
        item=ChinanewsItem()
        id = newurl.split('/')[-1].split('.')[0]
        clas = newurl.split('/')[5]
        title = response.xpath(f'//*[@id="{id}"]/text()')[0]
        title=title.get()
        timee = response.xpath('/html/body/div[1]/div[2]/div/div[1]/div[1]/div[1]/div[3]/span[1]/i/text()')[0]

        now = int(timee.get())
        timeArray = time.localtime(now / 1000)
        otherStyleTime = time.strftime("%Y-%m-%d", timeArray)
        Released = "发布时间:" + otherStyleTime
        imgurl = response.xpath('/html/body/div[1]/div[2]/div/div[1]/div[1]/div[1]//img/@src')
        imgurl=imgurl.getall()
        if imgurl == []:
            imgurl = "无图片"
        Imageannotations = response.xpath('/html/body/div[1]/div[2]/div/div[1]/div[1]/div[1]/div[4]/div/p/b/text()')  # b标签含有图片来源
        Imageannotations = Imageannotations.getall()
        Imageannotationstrue = []
        for i in Imageannotations:
            if "图片来源" in i:
                Imageannotationstrue.append(i)
        if Imageannotationstrue == []:
            Imageannotationstrue = "无图片注释"

        texts = response.xpath(
            '/html/body/div[1]/div[2]/div/div[1]/div[1]/div[1]/div[4]/div/p[@style="text-indent:2em;"]//text()')
        texts=texts.getall()
        text = [item for item in texts if item.strip()]

        # print(imgurl,Imageannotations)
        if len(text) > 1:
            summary = text[0]
            del text[0]
            body = ""
            for i in text:
                body = body + '\n' + i
        else:
            summary = []
            body = []
        if body!=[]:
            item["list"]=[id, clas, title, otherStyleTime, Released, str(imgurl), str(Imageannotationstrue), summary,
                body, newurl]

            yield item
        else:
            id = newurl.split('/')[-1].split('.')[0]
            clas = newurl.split('/')[5]
            title = response.xpath(f'//*[@id="{id}"]/text()')[0]
            title=title.get()
            timee = response.xpath('/html/body/div[1]/div[2]/div/div[1]/div[1]/div[1]/div[3]/span[1]/i/text()')[0]
            now = int(timee.get())
            timeArray = time.localtime(now / 1000)
            otherStyleTime = time.strftime("%Y-%m-%d", timeArray)
            Released = "发布时间:" + otherStyleTime
            imgurl = response.xpath('/html/body/div[1]/div[2]/div/div[1]/div[1]/div[1]//img/@src')
            imgurl=imgurl.getall()
            if imgurl == []:
                imgurl = "无图片"
            Imageannotations = response.xpath(
                '/html/body/div[1]/div[2]/div/div[1]/div[1]/div[1]/div[4]/div/p/b/text()')  # b标签含有图片来源
            Imageannotations= Imageannotations.getall()
            Imageannotationstrue = []
            for i in Imageannotations:
                if "图片来源" in i:
                    Imageannotationstrue.append(i)
            if Imageannotationstrue == []:
                Imageannotationstrue = "无图片注释"
            text = response.xpath('/html/body/div[1]/div[2]/div/div[1]/div[1]/div[1]/div[4]/div/p/span/text()')
            text= text.getall()
            try:
                summary = response.xpath('/html/body/div[1]/div[2]/div/div[1]/div[1]/div[1]/div[4]/p/text()')[0]
                summary = summary.get()
            except:
                summary=[]
            item["list"]= [id, clas, title, otherStyleTime, Released, str(imgurl), str(Imageannotationstrue), summary,
                    str(text), newurl]
            yield item

起始url为’https://cms.offshoremedia.net/front/list/latest?pageNum=1&pageSize=15&siteId=694841922577108992&channelId=780811183157682176’
在这里插入图片描述
1.返回的数据为此页每个新闻的详细页面信息获取后将数据传递给parse()函数
2.parse()函数对数据进行提取提取出新闻页详细url然后发送请求并将结果交给datas()

yield scrapy.Request(url=newurl,callback=self.datas,cb_kwargs={'newurl': newurl},dont_filter=True)

3.datas()通过xpath对信息进行提取然后将数据提交给管道*

4.s=s+1更新url实现自动翻页然后通过yield scrapy.Request(url=url, callback=self.parse)将数据重新回调给parse()进入循环

三.管道存储

传统的同步数据库操作可能会导致Scrapy爬虫阻塞,等待数据库操作完成。而adbapi允许Scrapy以异步的方式与数据库进行交互。这意味着Scrapy可以在等待数据库操作完成的同时继续执行其他任务,如抓取更多的网页或解析数据。这种异步处理方式极大地提高了Scrapy的运行效率和性能,使得项目能够更快地处理大量数据。

import logging
from twisted.enterprise import adbapi
import pymysql
class ChinanewsPipeline2:

    def __init__(self):
        self.dbpool = adbapi.ConnectionPool(
            'pymysql',
                        host='127.0.0.1',
                        user='root',
                        password='root',
                        port=3306,
                        database='news',
        )

    def process_item(self, item, spider):
        self.dbpool.runInteraction(self._do_insert, item["list"])

    def _do_insert(self, txn, list):
        sql = """INSERT INTO untitled (id, clas, title, otherStyleTime, Released, imgurl, Imageannotations, summary, body, url) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
            # txn是一个事务对象,用于执行SQL语句
        try:
            txn.execute(sql, tuple(list))
        except pymysql.err.IntegrityError:
            # 处理重复键错误,例如记录日志或忽略
            print(f"Duplicate entry for id {list[0]}, skipping...")

四.settings文件

# Scrapy settings for chinanews project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'chinanews'
LOG_LEVEL = 'ERROR'
SPIDER_MODULES = ['chinanews.spiders']
NEWSPIDER_MODULE = 'chinanews.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'chinanews (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
CONCURRENT_REQUESTS = 100

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
CONCURRENT_REQUESTS_PER_DOMAIN = 150
CONCURRENT_REQUESTS_PER_IP = 150

# Disable cookies (enabled by default)
#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0',
'Origin':
'https://www.oushinet.com',
'Referer':
'https://www.oushinet.com/',
'Content-Type':
'application/json;charset=UTF-8'
}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'chinanews.middlewares.ChinanewsSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'chinanews.middlewares.ChinanewsDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   #'chinanews.pipelines.ChinanewsPipeline': 300,
'chinanews.pipelines.ChinanewsPipeline2': 200
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1932739.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

tinymce富文本支持word内容同时粘贴文字图片上传 vue2

效果图 先放文件 文件自取tinymce: tinymce富文本简单配置及word内容粘贴图片上传 封装tinymce 文件自取&#xff1a;tinymce: tinymce富文本简单配置及word内容粘贴图片上传 页面引用组件 <TinymceSimplify refTinymceSimplify v-model"knowledgeBlockItem.content…

vue使用audio 音频实现播放与关闭(可用于收到消息给提示音效)

这次项目中因为对接了即时通讯 IM&#xff0c;有个需求就是收到消息需要有个提示音效&#xff0c;所以这里就想到了用HTML5 提供的Audio 标签&#xff0c;用起来也是很方便&#xff0c;首先让产品给你个提示音效&#xff0c;然后你放在项目中&#xff0c;使用Audio 标签&#x…

HardeningMeter:一款针对二进制文件和系统安全强度的开源工具

关于HardeningMeter HardeningMeter是一款针对二进制文件和系统安全强度的开源工具&#xff0c;该工具基于纯Python开发&#xff0c;经过了开发人员的精心设计&#xff0c;可以帮助广大研究人员全面评估二进制文件和系统的安全强化程度。 功能特性 其强大的功能包括全面检查各…

【BUG】已解决:WslRegisterDistribution failed with error: 0x800701bc

已解决&#xff1a;WslRegisterDistribution failed with error: 0x800701bc 欢迎来到英杰社区https://bbs.csdn.net/topics/617804998 欢迎来到我的主页&#xff0c;我是博主英杰&#xff0c;211科班出身&#xff0c;就职于医疗科技公司&#xff0c;热衷分享知识&#xff0c;武…

Ubuntu22.04安装CUDA+CUDNN+Conda+PyTorch

步骤&#xff1a; 1、安装显卡驱动&#xff1b; 2、安装CUDA&#xff1b; 3、安装CUDNN&#xff1b; 4、安装Conda&#xff1b; 5、安装Pytorch。 一、系统和硬件信息 1、Ubuntu 22.04 2、显卡&#xff1a;4060Ti 二、安装显卡驱动 &#xff08;已经安装的可以跳过&a…

通过SchedulingConfigurer 接口完成动态定时任务

通过SchedulingConfigurer 接口完成动态定时任务 一.背景 在Spring中&#xff0c;除了使用Scheduled注解外&#xff0c;还可以通过实现SchedulingConfigurer接口来创建定时任务。它们之间的主要区别在于灵活性和动态性。Scheduled注解适用于固定周期的任务&#xff0c;一旦任…

【STM32 HAL库】I2S的使用

使用CubeIDE实现I2S发数据 1、配置I2S 我们的有效数据是32位的&#xff0c;使用飞利浦格式。 2、配置DMA **这里需要注意&#xff1a;**i2s的DR寄存器是16位的&#xff0c;如果需要发送32位的数据&#xff0c;是需要写两次DR寄存器的&#xff0c;所以DMA的外设数据宽度设置16…

JavaWeb服务器-Tomcat(Tomcat概述、Tomcat的下载、安装与卸载、启动与关闭、常见的问题)

Tomcat概述 Tomcat服务器软件是一个免费的开源的web应用服务器。是Apache软件基金会的一个核心项目。由Apache&#xff0c;Sun和其他一些公司及个人共同开发而成。 由于Tomcat只支持Servlet/JSP少量JavaEE规范&#xff0c;所以是一个开源免费的轻量级Web服务器。 JavaEE规范&…

Vscode中Github copilot插件无法使用(出现感叹号)解决方案

1、击扩展或ctrl shift x ​​​​​​​ 2、搜索查询或翻找到Github compilot 3、点击插件并再左侧点击登录github 点击Sign up for a ... 4、跳转至github登录页&#xff0c;输入令牌完成登陆后返回VScode 5、插件可以正常使用

uni-app:文字竖直排列,并且在父级view中水平竖直对齐

一、效果 二、代码 <template><view class"parent"><text class"child">这是竖直排列的文字</text></view> </template> <script>export default {data() {return {}},methods: {},}; </script> <sty…

FATE Flow 源码解析 - 日志输出机制

背景介绍 在 之前的文章 中介绍了 FATE 的作业处理流程&#xff0c;在实际的使用过程中&#xff0c;为了查找执行中的异常&#xff0c;需要借助运行生成的日志&#xff0c;但是 FATE-Flow 包含的流程比较复杂&#xff0c;对应的日志也很多&#xff0c;而且分散在不同的文件中&…

windows和linux的等保加固测评的经验分享

一头等保加固测评的牛马&#xff0c;需要能做到一下午测评n个服务器 接下来就讲讲如何当一头xxxxxxxxx》严肃的等保测评加固的经验分享&#xff08; 一、window等保 首先你要自己按着教程在虚拟机做过一遍&#xff08;win2012和win2008都做过一遍&#xff0c;大概windows的…

抖音短视频seo矩阵系统源码(搭建技术开发分享)

#抖音矩阵系统源码开发 #短视频矩阵系统源码开发 #短视频seo源码开发 一、 抖音短视频seo矩阵系统源码开发&#xff0c;需要掌握以下技术&#xff1a; 网络编程&#xff1a;能够使用Python、Java或其他编程语言进行网络编程&#xff0c;比如使用爬虫技术从抖音平台获取数据。…

How to integrate GPT-4 model hosted on Azure with the gptstudio package

题意&#xff1a;怎样将托管在Azure上的GPT-4模型与gptstudio包集成&#xff1f; 问题背景&#xff1a; I am looking to integrate the OpenAI GPT-4 model into my application. Here are the details I have: Endpoint: https://xxxxxxxxxxxxxxx.openai.azure.com/Locatio…

Gradio从入门到精通(8)---基础组件介绍2

文章目录 一、基础组件详解1.Dropdown2.Image3.Audio4.File 总结 一、基础组件详解 1.Dropdown 用途&#xff1a; 提供下拉菜单选项。 初始化参数&#xff1a; choices: 可选择的选项列表。 value: 默认选中的值。可以是字符串、列表或是一个可调用对象。 type: 组件返回…

【有效验证】解决SQLyog连接MYSQL的错误 1251 - Client does not support

目录 一、原因分析&#xff1a; 二、进入到mysql 三、查看当前加密方式 四、更改加密方式 五、查看是否成功 前言&#xff1a;使用一个开源软件使用sqlyog、navcat都报1251错误&#xff0c;网上都是提示升级客户端&#xff0c;还有一种就是修改mysql配置。本文就是修改配置…

逆向案例二十三——请求头参数加密,某区块链交易逆向

网址&#xff1a;aHR0cHM6Ly93d3cub2tsaW5rLmNvbS96aC1oYW5zL2J0Yy90eC1saXN0L3BhZ2UvNAo 抓包分析&#xff0c;发现请求头有X-Apikey参数加密&#xff0c;其他表单和返回内容没有加密。 直接搜索关键字&#xff0c;X-Apikey&#xff0c;找到疑似加密位置&#xff0c;注意这里…

R语言实现SVM算法——分类与回归

### 11.6 基于支持向量机进行类别预测 ### # 构建数据子集 X <- iris[iris$Species! virginica,2:3] # 自变量&#xff1a;Sepal.Width, Petal.Length y <- iris[iris$Species ! virginica,Species] # 因变量 plot(X,col y,pch as.numeric(y)15,cex 1.5) # 绘制散点图…

【DGL系列】DGLGraph.out_edges简介

转载请注明出处&#xff1a;小锋学长生活大爆炸[xfxuezhagn.cn] 如果本文帮助到了你&#xff0c;欢迎[点赞、收藏、关注]哦~ 目录 函数说明 用法示例 示例 1: 获取所有边的源节点和目标节点 示例 2: 获取特定节点的出边 示例 3: 获取所有边的边ID 示例 4: 获取所有信息&a…

【概率论三】参数估计:点估计(矩估计、极大似然法)、区间估计

文章目录 一. 点估计1. 矩估计法2. 极大似然法2.1. 似然函数2.2. 极大似然估计法 3. 评价估计量的标准3.1. 无偏性3.2. 有效性3.3. 一致性 二. 区间估计1. 区间估计的概念2. 正态总体参数的区间估计 参数估计讲什么 由样本来确定未知参数参数估计分为点估计与区间估计 一. 点估…