網絡爬蟲--22.【CrawlSpider實戰】實現微信小程序社區爬蟲

文章目錄

  • 一. CrawlSpider
  • 二. CrawlSpider案例
    • 1. 目錄結構
    • 2. wxapp_spider.py
    • 3. items.py
    • 4. pipelines.py
    • 5. settings.py
    • 6. start.py
  • 三. 重點總結

一. CrawlSpider

現實情況下,我們需要對滿足某個特定條件的url進行爬取,這時候就可以通過CrawlSpider完成。

CrawlSpider繼承自Spider,只不過在之前的基礎上增加了新的功能,可以定義爬取的url規則,Scrapy碰到滿足條件的url都進行爬取,而不用手動的yield Request。

在這里插入圖片描述
在這里插入圖片描述

在這里插入圖片描述

二. CrawlSpider案例

1. 目錄結構

在這里插入圖片描述

2. wxapp_spider.py

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from wxapp.items import WxappItemclass WxappSpiderSpider(CrawlSpider):name = 'wxapp_spider'allowed_domains = ['wxapp-union.com']start_urls = ['http://www.wxapp-union.com/portal.php?mod=list&catid=1&page=1']rules = (Rule(LinkExtractor(allow=r'.+mod=list&catid=1&page=\d'),  follow=True),Rule(LinkExtractor(allow=r'.+article-.+\.html'), callback='parse_detail', follow=False))def parse_detail(self, response):title = response.xpath("//h1[@class='ph']/text()").get()# print(title)author_p = response.xpath(".//p[@class='authors']")author = author_p.xpath("./a/text()").get()pub_time = author_p.xpath("./span/text()").get()# print('author:%s/pub_time:%s'%(author,pub_time))article_content = response.xpath(".//td[@id='article_content']//text()").getall()content = "".join(article_content).strip()# print(content)# print('-'*30)item = WxappItem(title=title,author=author,pub_time=pub_time,content=content)yield item

3. items.py

# -*- coding: utf-8 -*-# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.htmlimport scrapyclass WxappItem(scrapy.Item):# define the fields for your item here like:title = scrapy.Field()author = scrapy.Field()pub_time = scrapy.Field()content = scrapy.Field()

4. pipelines.py

# -*- coding: utf-8 -*-# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exporters import JsonLinesItemExporterclass WxappPipeline(object):def __init__(self):self.fp = open('wxjc.json','wb')self.exporter = JsonLinesItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')def process_item(self, item, spider):self.exporter.export_item(item)return itemdef close_spider(self,spider):self.fp.close()

5. settings.py

# -*- coding: utf-8 -*-# Scrapy settings for wxapp 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.htmlBOT_NAME = 'wxapp'SPIDER_MODULES = ['wxapp.spiders']
NEWSPIDER_MODULE = 'wxapp.spiders'# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'wxapp (+http://www.yourdomain.com)'# Obey robots.txt rules
ROBOTSTXT_OBEY = False# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32# 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 = 1
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16# 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 = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Language': 'en','User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36'
}# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'wxapp.middlewares.WxappSpiderMiddleware': 543,
#}# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'wxapp.middlewares.WxappDownloaderMiddleware': 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 = {'wxapp.pipelines.WxappPipeline': 300,
}# 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'

6. start.py

from scrapy import cmdlinecmdline.execute("scrapy crawl wxapp_spider".split())

三. 重點總結

在這里插入圖片描述

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/451952.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/451952.shtml
英文地址,請注明出處:http://en.pswp.cn/news/451952.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

可以生成自動文檔的注釋

使用/**和*/可以用來自動的生成文檔。 這種注釋以/**開頭,以*/結尾

怎么安裝Scrapy框架以及安裝時出現的一系列錯誤(win7 64位 python3 pycharm)

因為要學習爬蟲,就打算安裝Scrapy框架,以下是我安裝該模塊的步驟,適合于剛入門的小白: 一、打開pycharm,依次點擊File---->setting---->Project----->Project Interpreter,打開后,可以…

illegal to have multiple occurrences of contentType with different values 解決

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。 在網上查到說是:“包含頁面與被包含頁面的page指令里面的contentType不一致,仔細檢查兩個文件第一行的 page....…

xpath-helper: 谷歌瀏覽器安裝xpath helper 插件

1.下載文件xpath-helper.crx xpath鏈接:https://pan.baidu.com/s/1dFgzBSd 密碼:zwvb,感謝這位網友,我從這拿到了 2.在Google瀏覽器里邊找到這個“擴展程序”選項菜單即可。 3.然后就會進入到擴展插件的界面了,把下載好的離線插件…

網絡爬蟲--23.動態網頁數據抓取

文章目錄一. Ajax二. 獲取Ajax數據的方式三. seleniumchromedriver獲取動態數據四. selenium基本操作一. Ajax 二. 獲取Ajax數據的方式 三. seleniumchromedriver獲取動態數據 selenium文檔:https://selenium-python.readthedocs.io/installation.html 四. sele…

視音頻編解碼技術及其實現

核心提示:一、視音頻編碼國際標準化組織及其壓縮標準介紹 國際上有兩個負責視音頻編碼的標準化組織,一個是VCEG(VideocodeExpertGroup),是國際電信聯合會下的視頻編碼專家組,一個是MPEG(MotionP…

什么是NaN

NaN,是Not a Number的縮寫。NaN 用于處理計算中出現的錯誤情況,比如 0.0 除以 0.0 或者求負數的平方根。由上面的表中可以看出,對于單精度浮點數,NaN 表示為指數為 emax 1 128(指數域全為 1),…

排序系列【比較排序系列之】直接插入排序

最近在和小伙伴們一起研究排序,排序分好多總,后期會做整體總結,本篇則主要對插入排序進行一個整理。 插入排序(insert sorting)的算法思想十分簡單,就是對待排序的記錄逐個進行處理,每個新紀錄…

Mysql 無法插入中文,中文亂碼解決

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。 在計算機中搜索 my.ini文件 找到后打開 ,并找到這2行作 如下設置 : default-character-setutf8character-se…

gcc g++安裝

2019獨角獸企業重金招聘Python工程師標準>>> 安裝之前要卸載掉老版本的gcc、g sudo apt-get remove gccgcc-xx #可能有多個版本,都要刪掉 sudo apt-get remove g sudo apt-get install gcc 安裝g編譯器,可以通過命令 sudo apt-get installb…

網絡爬蟲--24.【selenium實戰】實現拉勾網爬蟲之--分析接口獲取數據

文章目錄一. 思路概述二. 分析數據接口三. 詳細代碼一. 思路概述 1.拉勾網采用Ajax技術,加載網頁時會向后端發送Ajax異步請求,因此首先找到數據接口; 2.后端會返回json的數據,分析數據,找到單個招聘對應的positionId…

18條工作感想:不要不情愿地工作

18條工作感想:不要不情愿地工作。人生有兩個基點支撐:家庭與工作。對工作不滿意,就是毀掉一半的人生。 001 不要不情愿地工作。不情愿,就一定沒熱情,沒激情,沒動力,就不會用心……那么&#xf…

bzoj 1999: [Noip2007]Core樹網的核【樹的直徑+單調隊列】

我要懶死了&#xff0c;所以依然是lyd的課件截圖 注意是min{max(max(d[uk]),dis(u1,ui),dis(uj,un))}&#xff0c;每次都從這三個的max里取min #include<iostream> #include<cstdio> using namespace std; const int N500005; int n,m,h[N],cnt,d[N],s,t,mx,f[N],a…

01-匯編初學

0、前言 對于一個iOS App來說&#xff0c;它其實就是一個安裝在手機中的可執行文件&#xff0c;這個可執行文件本質上是二進制文件&#xff0c;它由iPhone手機上的CPU執行。如果我們需要對操作系統、App進行深入了解&#xff0c;以及App的逆向都需要我們熟悉匯編語言 1、匯編語…

jquery.dataTables.min.js:62 Uncaught TypeError: Cannot read property ‘style‘ of undefined原因

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 報錯&#xff1a; jquery.dataTables.min.js:62 Uncaught TypeError: Cannot read property style of undefined 原因&#xff1a;data…

ASCII Unicode GBK UTF的聯系

快下班時&#xff0c;愛問問題的小朋友Nico又問了一個問題&#xff1a; "sqlserver里面有char和nchar&#xff0c;那個n據說是指unicode的數據&#xff0c;這個是什么意思。" 并不是所有簡單的問題都很容易回答&#xff0c;就像這個問題一樣。于是我答應專門寫一篇BL…

網絡爬蟲--25.【selenium實戰】實現拉勾網爬蟲之--selenium獲取數據

代碼實現 #encoding: utf-8from selenium import webdriver from lxml import etree import re import time from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by…

Java 設計模式-【單例模式】

單例解決了什么問題&#xff1a;為了節約系統資源&#xff0c;有時需要確保系統中某個類只有唯一一個實例&#xff0c;當這個唯一實例創建成功之后&#xff0c;我們無法再創建一個同類型的其他對象&#xff0c;所有的操作都只能基于這個唯一實例。為了確保對象的唯一性&#xf…

Lua游戲開發----模塊

1&#xff1a;游戲目錄結構對模塊的理解&#xff1a; Base&#xff0c;Common&#xff0c;Game這三個文件夾下都有自己的moduleConfig文件。 base文件夾下的moduleConfig.lua文件是存放游戲基礎的模塊&#xff08;例如&#xff1a;游戲視圖準備&#xff0c;發牌&#xff0c;托管…

css 引用 方法

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 CSS 樣式一共 3 中使用方法 ——內聯式樣式表行樣式<div style"color:#000;"></div>只能操作1個標簽&#xff0…