search
HomeBackend DevelopmentPython Tutorial使用scrapy实现爬网站例子和实现网络爬虫(蜘蛛)的步骤

代码如下:


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector

from cnbeta.items import CnbetaItem
class CBSpider(CrawlSpider):
    name = 'cnbeta'
    allowed_domains = ['cnbeta.com']
    start_urls = ['http://www.bitsCN.com']

    rules = (
        Rule(SgmlLinkExtractor(allow=('/articles/.*\.htm', )),
             callback='parse_page', follow=True),
    )

    def parse_page(self, response):
        item = CnbetaItem()
        sel = Selector(response)
        item['title'] = sel.xpath('//title/text()').extract()
        item['url'] = response.url
        return item



实现蜘蛛爬虫步骤

1.实例初级目标:从一个网站的列表页抓取文章列表,然后存入数据库中,数据库包括文章标题、链接、时间

首先生成一个项目:scrapy startproject fjsen
先定义下items,打开items.py:

我们开始建模的项目,我们想抓取的标题,地址和时间的网站,我们定义域为这三个属性。这样做,我们编辑items.py,发现在开放目录目录。我们的项目看起来像这样:

代码如下:


from scrapy.item import Item, Field
class FjsenItem(Item):
    # define the fields for your item here like:
    # name = Field()
    title=Field()
    link=Field()
    addtime=Field()

第二步:定义一个spider,就是爬行蜘蛛(注意在工程的spiders文件夹下),他们确定一个初步清单的网址下载,如何跟随链接,以及如何分析这些内容的页面中提取项目(我们要抓取的网站是http://www.fjsen.com/j/node_94962.htm 这列表的所有十页的链接和时间)。
新建一个fjsen_spider.py,内容如下:

代码如下:


#-*- coding: utf-8 -*-
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from fjsen.items import FjsenItem
class FjsenSpider(BaseSpider):
    name="fjsen"
    allowed_domains=["fjsen.com"]
    start_urls=['http://www.fjsen.com/j/node_94962_'+str(x)+'.htm' for x in range(2,11)]+['http://www.fjsen.com/j/node_94962.htm']
    def parse(self,response):
        hxs=HtmlXPathSelector(response)
        sites=hxs.select('//ul/li')
        items=[]
        for site in sites:
            item=FjsenItem()
            item['title']=site.select('a/text()').extract()
            item['link'] = site.select('a/@href').extract()
            item['addtime']=site.select('span/text()').extract()
            items.append(item)
        return items                 

name:是确定蜘蛛的名称。它必须是独特的,就是说,你不能设置相同的名称不同的蜘蛛。
allowed_domains:这个很明显,就是允许的域名,或者说爬虫所允许抓取的范围仅限这个列表里面的域名。
start_urls:是一个网址列表,蜘蛛会开始爬。所以,第一页将被列在这里下载。随后的网址将生成先后从数据中包含的起始网址。我这里直接是列出十个列表页。
parse():是蜘蛛的一个方法,当每一个开始下载的url返回的Response对象都会执行该函数。
这里面,我抓取每一个列表页中的

    下的
  • 下的数据,包括title,链接,还有时间,并插入到一个列表中


    第三步,将抓取到的数据存入数据库中,这里就得在pipelines.py这个文件里面修改了

    代码如下:


    # Define your item pipelines here
    #
    # Don't forget to add your pipeline to the ITEM_PIPELINES setting
    from os import path
    from scrapy import signals
    from scrapy.xlib.pydispatch import dispatcher
    class FjsenPipeline(object):

        def __init__(self):
            self.conn=None
            dispatcher.connect(self.initialize,signals.engine_started)
            dispatcher.connect(self.finalize,signals.engine_stopped)
        def process_item(self,item,spider):
            self.conn.execute('insert into fjsen values(?,?,?,?)',(None,item['title'][0],'http://www.bitsCN.com/'+item['link'][0],item['addtime'][0]))
            return item
        def initialize(self):
            if path.exists(self.filename):
                self.conn=sqlite3.connect(self.filename)
            else:
                self.conn=self.create_table(self.filename)
        def finalize(self):
            if self.conn is not None:
                self.conn.commit()
                self.conn.close()
                self.conn=None
        def create_table(self,filename):
            conn=sqlite3.connect(filename)
            conn.execute("""create table fjsen(id integer primary key autoincrement,title text,link text,addtime text)""")
            conn.commit()
            return conn

    这里我暂时不解释,先继续,让这个蜘蛛跑起来再说。

    第四步:修改setting.py这个文件:将下面这句话加进去

    代码如下:


    ITEM_PIPELINES=['fjsen.pipelines.FjsenPipeline']

    接着,跑起来吧,执行:

    代码如下:


    scrapy crawl fjsen


    就会在目前下生成一个data.sqlite的数据库文件,所有抓取到的数据都会存在这里。
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),