用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.pswp.cn/news/278554.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/278554.shtml
英文地址,請注明出處:http://en.pswp.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