用scrapy框架写爬虫

结构图

爬虫可以发送给引擎的两种请求:

    # 1、url:# (爬虫)yield scrapy.Request -> 引擎 -> 调度器(发送给调度器入队) -> 引擎(调度器出队请求于引擎)# -> 下载器(引擎发送于下载器) -> 引擎(下载器成功(失败)返回引擎):-> 爬虫(引擎接收成功将给爬虫response)or -> 调度器(失败给调度器重新下载)# -> 引擎(爬虫接收response并做处理,发送跟进url:yield scrapy.Request) -> 调度器(引擎发送给调度器入队) ->...# 2、weiboitem:# 一般在接收response后便有了数据,然后# (爬虫) yield weiboitem -> 引擎 -> pipelines(管道)进行存储,管道中自己写存储代码 -> mysql or redis

一、准备工作

  • python、pip、scrapy(pip install Scrapy)
  • 测试:scrapy fetch http://www.baidu.com

二、构建crapy框架

  • 创建爬虫项目(cmd或terminal):scrapy startproject mySpiderName
  • cd:cd mySpider
  • 创建爬虫:scrapy genspider myspidername www.dytt8.net
    ( www.dytt8.net 是要爬取网址的根域名,只有在此根域名才能爬取到内容)
  • 修改settings协议: ROBOTSTXT_OBEY = False
  • 切记在settings中ITEM_PIPELINES列表添加语句(打开注释),否则管道不会被执行:
    ‘mySpiderName.pipelines.WeiboSpiderPipeline’: 300,

三、填写代码三部曲

  • 在自动生成的spiders文件夹下的myspider.py文件中编辑:
import scrapy
from hotnewsSpider.items import WeiboSpiderItem     # hotnewsSpider为项目名,WeiboSpiderItem为爬虫item类,在items.py中可找到# 创建第二个爬虫时需要手动在items中添加此类from bs4 import BeautifulSoupclass WeiboSpider(scrapy.Spider):# 以微博为例:name = 'weibo'                          # 爬虫名 -- 自动生成,唯一,不可变allowed_domains = ['s.weibo.com']       # 允许访问的根域名start_urls = ['http://s.weibo.com/']    # 起始访问地址searchName = "张钧甯 感谢抬爱"headers = {}cookies = {}urls = [# 模拟搜索 searchName"https://s.weibo.com/weibo?q=%s&Refer=SWeibo_box"%searchName]# urls.extend(start_urls)# 重写起始请求,可以给请求加上许多信息def start_requests(self):# 发送初始请求for url in self.urls:yield scrapy.Request(url=url, headers=self.headers, cookies=self.cookies, callback=self.parse)# 默认第一次返回response接收函数,第二次response可以继续返回这里,也可以返回你定义的人一个函数中,# 这在yield scrapy.Request(url,callback=self.your_parse)中决定def parse(self, response):# 用爬虫对应的item类声明一个对象,类型为字典,用来保存数据,通过 yield weiboitem 返回给引擎weiboitem = WeiboSpiderItem()                       # from hotnewsSpider.items import WeiboSpiderItem# BeautifulSoup代码块:html = response.textsoup = BeautifulSoup(html, 'lxml')content_id_div = soup.find(id='pl_feedlist_index')card_wraps = content_id_div.find_all(class_='card-wrap')id = 0for card_wrap_item in card_wraps:# 用户名username = card_wrap_item.find(class_='info').find(class_='name').text# 用户头像user_headimg = card_wrap_item.find(class_='avator').find('img')['src']# 内容# 文字 偶尔会搜索出某个人content_text_html = card_wrap_item.find(class_='txt')content_text = ''if content_text_html:content_text = content_text_html.get_text().replace(' ', '').replace('\n', '').replace('展开全文c', '')# 图片 有的无图img_items_html = card_wrap_item.find(class_='m3')content_imgs = []if img_items_html:for img_item in img_items_html.find_all('img'):content_imgs.append(img_item['src'])# (收藏)、转发、评论、点赞数量other_items_html = card_wrap_item.find(class_='card-act')other_items_dic = {}if other_items_html:other_items_lst = other_items_html.find_all('a')for other_item_index in range(len(other_items_lst)):if other_item_index == 0:other_items_dic['收藏'] = ""elif other_item_index == 1:other_items_dic['转发'] = other_items_lst[other_item_index].text.strip().split()[1]elif other_item_index == 2:other_items_dic['评论'] = other_items_lst[other_item_index].text.strip().split()[1]else:other_items_dic['点赞'] = other_items_lst[other_item_index].text.strip()# print(other_items_dic)id += 1weiboitem['id'] = idweiboitem['username'] = usernameweiboitem['user_headimg'] = user_headimgweiboitem['content_text'] = content_textweiboitem['content_imgs'] = content_imgsweiboitem['other_items_dic'] = other_items_dicyield weiboitem		# 返回数据给引擎,引擎将其传入管道执行管道中的代码# yield scrapy.Request(url,callback=self.parse)	# 返回跟进url给引擎# yield scrapy.Request(url,callback=self.parse2)	# 返回跟进url给引擎break       # 用于测试,只拿一次数据def parse2(self,response):pass
  • 在items.py中初始化item字典(第二次以上新建的爬虫需要自己新增对应类)
import scrapy# 第一个爬虫对应的item类,在创建项目时自动产生
class HotnewsspiderItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()pass# 自己新增的爬虫类
class WeiboSpiderItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()id = scrapy.Field()username = scrapy.Field()user_headimg = scrapy.Field()content_text = scrapy.Field()content_imgs = scrapy.Field()other_items_dic = scrapy.Field()pass
  • 在pipelines.py中保存数据
# 第一个爬虫对应的Pipeline类,在创建项目时自动产生
class HotnewsspiderPipeline(object):def process_item(self, item, spider):pass# return item# 自己新增的爬虫类
# 切记在settings中ITEM_PIPELINES列表添加语句,否则不会被执行:
# 'hotnewsSpider.pipelines.WeiboSpiderPipeline': 300,
class WeiboSpiderPipeline(object):def process_item(self, item, spider):# 在这里将数据存入mysql,redisprint(item)

运行:

  • scrapy crawl mysipdername(别忘了cd目录)
  • 添加以下任意一个py运行文件命名run或main,要与scrapy.cfg文件同级目录
    更改自己的爬虫名即可右键运行
一、
from scrapy.cmdline import execute
import sys
import os'''
运行scrapy爬虫的方式是在命令行输入    scrapy crawl <spider_name>
调试的常用方式是在命令行输入          scrapy shell <url_name>
'''sys.path.append(os.path.dirname(os.path.abspath(__file__)))execute(['scrapy', 'crawl', 'weibo'])  # 你需要将此处的spider_name替换为你自己的爬虫名称
二、
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings'''
运行scrapy爬虫的方式是在命令行输入    scrapy crawl <spider_name>
调试的常用方式是在命令行输入          scrapy shell <url_name>
'''if __name__ == '__main__':process = CrawlerProcess(get_project_settings())process.crawl('weibo')    #  你需要将此处的spider_name替换为你自己的爬虫名称process.start()

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

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

相关文章

audacity_如何在Audacity中快速编辑多个文件

audacityGot a bunch of files that need to be edited the same way? You can automate the process to save time and effort using Audacity’s Chain feature and modify tons of files at the same time. 有一堆需要以相同方式编辑的文件&#xff1f; 您可以使用Audacity…

通过api管理grafana

1. 生成api key 参考&#xff1a; http://docs.grafana.org/http_api/auth/ 2.点击添加后&#xff0c;生成了个获取一个deshboards的api样例 3.放到linux上运行测试&#xff0c;结果成功返回。 4. 有些api并不支持使用api key 来连接&#xff0c;如下图中的搜索用户接口&#x…

NFS服务的配置过程

NFS服务的配置过程服务端:1)安装nfs和rcp服务yum install nfs-utils rpcbind -y 因为NFS支持的功能多,不同的功能会使用不同的程序来启动每启动一个功能就会启动一些端口来传输数据,默认NFS读完启动会产生多个进程,多个端口号信息,会随机使用未被使用的端口重启又会变化,所以…

vue项目将token存在(vuex)store和localstorage中

文章目录一、准备工作和token1、准备工作2、介绍token用法二、创建storage&#xff0c;store&#xff0c;request1、src目录&#xff1a;2、封装storage&#xff08;可选&#xff09;3、创建store4、创建request三、配置代理&#xff0c;封装路由router、设置路由守卫&#xff…

安卓手电筒_将价值10美元的手电筒砍入超高亮高级灯中

安卓手电筒If you’re looking for a bright flashlight without paying an arm and a leg this simple hack modifies a cheap $10 flashlight to be as bright as a $95 one. 如果您要寻找一个明亮的手电筒而又不用付胳膊和腿&#xff0c;这个简单的技巧就可以将便宜的10美元…

初识 scrapy 框架 - 安装

前面豆子学习了基本的urllib的模块&#xff0c;通过这个模块可以写一些简单的爬虫文件。如果要处理大中型的爬虫项目&#xff0c;urllib就显得比较low了&#xff0c;这个时候可以使用scrapy框架来实现&#xff0c;很多基本的处理在scrapy里面已经做好了。 首先来安装一下。推荐…

Vue使用Vuex一步步封装并使用store

文章目录一、安装Vuex依赖二、一步步封装store1. main.js中全局引入store仓库&#xff08;下一步创建&#xff09;2. this.$store3. this.$store.state4. this.$store.getters&#xff08;this. $store.state的升级&#xff09;5. this.$store.commit(mutations)6. this.$store…

linux自学(四)之开始centos学习,网络配置

上一篇&#xff1a;linux自学&#xff08;三&#xff09;之开启虚拟机 安装好镜像之后&#xff0c;重启之后需要登录&#xff0c;我这里直接是root账号直接登录的&#xff0c;注意&#xff1a;输入密码的时候不显示。 之后输入ifconfig最常用的命令来查看网卡信息&#xff0c;出…

k8s extender_Windows Home Server的Drive Extender的9种选择

k8s extenderNow that Microsoft has officially killed off the best part about Windows Home Server what can you do? Here are some alternatives for drive extender that you can use if you want to build a WHS of your own. 既然Microsoft正式取消了Windows Home Se…

为什么element的el-backtop会不管用,来看这里

<template>Scroll down to see the bottom-right button.<el-backtop target".page-component__scroll .el-scrollbar__wrap"></el-backtop> </template>把target指向你要产生“回到顶部”按钮的组件&#xff0c; 这个组件一定要是产生滚动条…

如何创建一份springboot的docker镜像

2019独角兽企业重金招聘Python工程师标准>>> FROM centos:7 ENV JAVA_HOME /usr/java/jdk1.7.0_55 ENV MAC_PUBLISH_PATH /home/app ENV LOG_PATH /var/log ENV PATH $JAVA_HOME/bin:$PATH ENV TIME_ZONE Asia/Shanghai COPY jdk-7u55-linux-x64.rpm /opt/ RUN mkd…

Xamarin.Android 开发中遇到旋转屏幕错误

错误信息 : System.NotSupportedException: Unable to find the default constructor on type App5.MyFragment. Please provide the missing constructor. 错误图片&#xff1a; 解决方法&#xff1a;干脆不让他旋转屏幕&#xff0c;当下QQ、微信等app都没有旋转等功能&#…

原生js打印指定节点元素

很简单&#xff08;可粘贴至txt文档后改后缀为html打开看效果&#xff09;&#xff1a; <!doctype html> <html lang"en"> <head><meta charset"utf-8"><title>打印</title><meta name"viewport" conte…

Android社会化分享详解

前言现如今app市场竞争激烈&#xff0c;做app不会放过任何推广自己的app的渠道&#xff0c;如果app中没有社会化分享功能&#xff0c;那真的是OUT了&#xff0c;我们先来看下一些app中的分享界面功能吧。现在主流的分享平台&#xff0c;一般用的都是微信、QQ、微博&#xff0c;…

windows7黑屏修复_如何在Windows 10更新后修复黑屏

windows7黑屏修复RealVector/Shutterstock.comRealVector / Shutterstock.comSome Windows 10 PCs have been rebooting to a black screen after installing the June 2019 cumulative update from Windows Update. This seems scary at first, but luckily there’s a quick …

[sol]250OJ 1~10

下载 转载于:https://www.cnblogs.com/yztblog/p/10208314.html

vue/cli4 创建vue项目选项详解

多版本创建项目一、vue-cli2.x二、vue-cli3.x三、vue-cli4.x1.查看 vue 版本&#xff1a; 项目中,找到package.json文件夹 找"dependencies"中的vue &#xff1b; 若无项目&#xff0c;在cmd中输入 where vue&#xff0c;cd到vue目录下输入 npm list vue &#xff0c…

java 商品评价计算算法

import java.io.Serializable; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.math.BigDecimal; import java.math.RoundingMode;/*** 商品评价算法* * project icomment* fileName ProductScore.java* Description* author light-z…

rainmeter使用教程_如何使用Rainmeter在桌面上显示报价

rainmeter使用教程I’ve never really been a desktop gadgets and widgets type of person, but I often put an inspirational quote on my desktop wallpaper. Today we’ll show you how to do this using Rainmeter, no matter what wallpaper you switch to. 我从来没有真…

Some code changes cannot be hot swapped into a running virtual machine

java运行中修改代码不能改变立刻应用到本次运行中转载于:https://www.cnblogs.com/Pusteblume/p/10211110.html