Practice the Python crawler framework Scrapy to capture the TOP250 Douban movie

Source: Internet
Author: User
This article describes how to use the Python crawler framework Scrapy to capture the TOP250 Douban movie. The environment in this article is based on the Windows operating system. For more information, see Install and deploy Scrapy

Before installing Scrapy, you must first determine that Python has been installed (currently Scrapy supports Python2.5, Python2.6, and Python2.7 ). The official document introduces three methods for installation, I use easy_install for installation, the first is to download the Windows version of setuptools (: http://pypi.python.org/pypi/setuptools), after the download all the way to NEXT on it.
After the setuptool is installed. Run CMD and then run the following command:

easy_install -U Scrapy

Similarly you can choose to install using pip, pip address: http://pypi.python.org/pypi/pip
The command for installing Scrapy using pip is

pip install Scrapy

If your computer has previously installed visual studio 2008 or visual studio 2010, Scrapy has been installed successfully. If the following error occurs: Unable to find vcvarsall. bat, you need to try again. You can install visual studio or use the following methods to solve the problem:
First install MinGW (MinGW: http://sourceforge.net/projects/mingw/files/ folder, find the BIND folder under the mingwinstallation directory, find mingw32-make.exe, copy a copy named make.exe;
Add the MinGW path to the environment variable path. For example, if I install MinGW in D: \ MinGW \, add D: \ MinGW \ bin to the path;
Open the command line window and enter the directory of the Code to be installed in the command line window;
Run the following command: setup. py install build-compiler = mingw32.

If "xslt-config" is not an internal or external command, it is not a executable program or batch file ." Error. The main cause is that lxml is not successfully installed. You only need to install it at http://pypi.python.org/simple/lxml/download an exefile.
Now you can go to the topic.

Create a project
Let's use crawlers to obtain information about the Top 250 Douban movies. Create a Scrapy project before you start. Because I use Win7, enter a directory in CMD where I want to save the code, and then execute:

D:\WEB\Python>scrapy startproject doubanmoive

This command will create a new directory doubanmoive under the current directory. The directory structure is as follows:

D:\WEB\Python\doubanmoive>tree /fFolder PATH listing for volume DataVolume serial number is 00000200 34EC:9CB9D:.│ scrapy.cfg│└─doubanmoive │ items.py │ pipelines.py │ settings.py │ __init__.py │ └─spiders   __init__.py

These files are mainly:

  • Doubanmoive/items. py: defines the content field to be obtained, similar to the object class.
  • Doubanmoive/pipelines. py: A project pipeline file used to process data captured by Spider.
  • Doubanmoive/settings. py: project configuration file
  • Doubanmoive/spiders: directory where spider is stored

Define a project (Item)

Item is the container used to load and capture data. It is similar to the Entity class in Java. Open doubanmoive/items. py and you can see that the following code is created by default.

from scrapy.item import Item, Fieldclass DoubanmoiveItem(Item):  pass

We only need to add the fields to be crawled in the Doubanmoive class, such as name = Field (). Finally, we need to complete the Code as follows.

From scrapy. item import Item, Fieldclass DoubanmoiveItem (Item): name = Field () # Movie name year = Field () # year score = Field () # = Field () # Director classification = Field () # category actor = Field () # actors

Write a crawler)

Spider is the core class of the entire project. In this class, we will define the crawling objects (domain names, URLs) and crawling rules. The tutorials in Scrapy official documents are based on BaseSpider, but BaseSpider can only crawl the given URL list and cannot expand outward based on an initial URL. In addition to BaseSpider, there are many classes that can directly inherit Spider, such as scrapy. contrib. spiders. crawler.

Create the moive_spider.py file in the doubanmoive/spiders directory and enter the code.

# -*- coding: utf-8 -*-from scrapy.selector import Selectorfrom scrapy.contrib.spiders import CrawlSpider,Rulefrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractorfrom doubanmoive.items import DoubanmoiveItemclass MoiveSpider(CrawlSpider): name="doubanmoive" allowed_domains=["movie.douban.com"] start_urls=["http://movie.douban.com/top250"] rules=[  Rule(SgmlLinkExtractor(allow=(r'http://movie.douban.com/top250\?start=\d+.*'))),  Rule(SgmlLinkExtractor(allow=(r'http://movie.douban.com/subject/\d+')),callback="parse_item"),   ] def parse_item(self,response):  sel=Selector(response)  item=DoubanmoiveItem()  item['name']=sel.xpath('//*[@id="content"]/h1/span[1]/text()').extract()  item['year']=sel.xpath('//*[@id="content"]/h1/span[2]/text()').re(r'\((\d+)\)')  item['score']=sel.xpath('//*[@id="interest_sectl"]/p/p[1]/strong/text()').extract()  item['director']=sel.xpath('//*[@id="info"]/span[1]/a/text()').extract()  item['classification']= sel.xpath('//span[@property="v:genre"]/text()').extract()  item['actor']= sel.xpath('//*[@id="info"]/span[3]/a[1]/text()').extract()  return item

Code Description: MoiveSpider inherits the CrawlSpider, name, allow_domains, and start_url in Scrapy to understand the meaning of the name. The rules is slightly more complex and defines the URL crawling rules, all links that match the allow regular expression are added to Scheduler (Scheduler ). By analyzing the pagination URL http://movie.douban.com/top250 of Douban movie Top250? Start = 25 & filter = & type = the following rules can be obtained:

Rule (SgmlLinkExtractor (allow = (r 'HTTP: // movie.douban.com/top250 \? Start = \ d + .*'))),
And the page we really want to crawl is a detailed introduction of every movie, such as the Salvation link of Xiao shenke for http://movie.douban.com/subject/1292052/, that only the number behind the subject is changed, according to the regular expression to get the following code. We need to capture the content in this type of link, so we add the callback attribute and give the Response to the parse_item function for processing.

Rule (SgmlLinkExtractor (allow = (r 'HTTP: // movie.douban.com/subject/?d='), callback = "parse_item "),
The processing logic in the parse_item function is very simple. Get the code that matches the condition link, and then assign the content to the item according to certain rules and return the Item Pipeline. To obtain most of the TAG content, you do not need to write complex regular expressions. You can use XPath. XPath is a language for searching information in XML documents, but it can also be used in HTML. The following table lists common expressions.

Expression Description
Nodename Select all child nodes of the node.
/ Select from the root node.
// Select the nodes in the document from the current node that matches the selected node, regardless of their location.
. Select the current node.
.. Select the parent node of the current node.
@ Select attributes.

For example, // * [@ id = "content"]/h1/span [1]/text () the obtained result is the text content of the first element in the span list under h1 element under any element whose id is content. We can use the Chrome developer tool (F12) to obtain the XPath expression of a specific content. The specific operation is to click the review element on the content to be crawled, and the developer tool will appear below, locate the element, right-click the content, and select copy XPath.

Store Data

After crawlers obtain data, they need to be stored in the database. Previously we mentioned that this operation needs to be processed by the project pipeline (pipeline). The common operations are as follows:

  • Clean HTML data
  • Verify the parsed data (check whether the project contains necessary fields)
  • Check whether the data is duplicated (delete the data if it is repeated)
  • Store parsed data in the database

Because we have various data formats, it is not convenient to store some data in relational databases, so I wrote another MongoDB after writing the MySQL Pipeline.

MySQL version:

#-*-Coding: UTF-8-*-from scrapy import logfrom twisted. enterprise import adbapifrom scrapy. http import Requestimport MySQLdbimport MySQLdb. cursorsclass DoubanmoivePipeline (object): def _ init _ (self): self. dbpool = adbapi. connectionPool ('mysqldb', db = 'python', user = 'root', passwd = 'root', cursorclass = MySQLdb. cursors. dictCursor, charset = 'utf8', use_unicode = False) def process_item (self, item, spider): query = self. dbpool. runInteraction (self. _ conditional_insert, item) query. addErrback (self. handle_error) return item def _ conditional_insert (self, tx, item): tx.exe cute ("select * from doubanmoive where m_name = % s ", (item ['name'] [0],) result = tx. fetchone () log. msg (result, level = log. DEBUG) print result if result: log. msg ("Item already stored in db: % s" % item, level = log. DEBUG) else: classification = actor = ''lenClassification = len (item ['classification ']) lenActor = len (item ['actor']) for n in xrange (lenClassification ): classification + = item ['classification '] [n] if n
 
  

MongoDB version:

# -*- coding: utf-8 -*-import pymongofrom scrapy.exceptions import DropItemfrom scrapy.conf import settingsfrom scrapy import logclass MongoDBPipeline(object): #Connect to the MongoDB database def __init__(self):  connection = pymongo.Connection(settings['MONGODB_SERVER'], settings['MONGODB_PORT'])  db = connection[settings['MONGODB_DB']]  self.collection = db[settings['MONGODB_COLLECTION']] def process_item(self, item, spider):  #Remove invalid data  valid = True  for data in item:   if not data:   valid = False   raise DropItem("Missing %s of blogpost from %s" %(data, item['url']))  if valid:  #Insert data into database   new_moive=[{    "name":item['name'][0],    "year":item['year'][0],    "score":item['score'][0],    "director":item['director'],    "classification":item['classification'],    "actor":item['actor']   }]   self.collection.insert(new_moive)   log.msg("Item wrote to MongoDB database %s/%s" %   (settings['MONGODB_DB'], settings['MONGODB_COLLECTION']),   level=log.DEBUG, spider=spider)   return item

It can be seen that the basic processing process is the same, but it is not convenient for MySQL to convert data of the array type through separators. MongoDB supports storing List, Dict, and other types of data.

Configuration File

You also need to add some configuration information in settings. py before running the crawler.

BOT_NAME = 'doubanmoive'SPIDER_MODULES = ['doubanmoive.spiders']NEWSPIDER_MODULE = 'doubanmoive.spiders'ITEM_PIPELINES={ 'doubanmoive.mongo_pipelines.MongoDBPipeline':300, 'doubanmoive.pipelines.DoubanmoivePipeline':400,}LOG_LEVEL='DEBUG'DOWNLOAD_DELAY = 2RANDOMIZE_DOWNLOAD_DELAY = TrueUSER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5'COOKIES_ENABLED = TrueMONGODB_SERVER = 'localhost'MONGODB_PORT = 27017MONGODB_DB = 'python'MONGODB_COLLECTION = 'test'

The ITEM_PIPELINES file defines two Pipeline files: MySQL and MongoDB. The following numbers indicate the execution priority. The value ranges from 0 ~ 1000. The DOWNLOAD_DELAY and other information in the middle are used to prevent crawlers from being banned by Douban and Increase random latency and browser proxy. The last step is the MongoDB configuration information. MySQL can also use this method for writing.

So far, crawlers that crawl Douban movies have been completed. Run Scrapy crawl doubanmoive in the command line to start crawling!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.