Home Backend Development Python Tutorial Python的Scrapy爬虫框架简单学习笔记

Python的Scrapy爬虫框架简单学习笔记

Jun 10, 2016 pm 03:06 PM
python scrapy reptile

 一、简单配置,获取单个网页上的内容。
(1)创建scrapy项目

scrapy startproject getblog
Copy after login

(2)编辑 items.py

# -*- coding: utf-8 -*-
 
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
 
from scrapy.item import Item, Field
 
class BlogItem(Item):
  title = Field()
  desc = Field()
Copy after login

(3)在 spiders 文件夹下,创建 blog_spider.py

需要熟悉下xpath选择,感觉跟JQuery选择器差不多,但是不如JQuery选择器用着舒服( w3school教程: http://www.w3school.com.cn/xpath/ )。

# coding=utf-8
 
from scrapy.spider import Spider
from getblog.items import BlogItem
from scrapy.selector import Selector
 
 
class BlogSpider(Spider):
  # 标识名称
  name = 'blog'
  # 起始地址
  start_urls = ['http://www.cnblogs.com/']
 
  def parse(self, response):
    sel = Selector(response) # Xptah 选择器
    # 选择所有含有class属性,值为‘post_item'的div 标签内容
    # 下面的 第2个div 的 所有内容
    sites = sel.xpath('//div[@class="post_item"]/div[2]')
    items = []
    for site in sites:
      item = BlogItem()
      # 选取h3标签下,a标签下,的文字内容 ‘text()'
      item['title'] = site.xpath('h3/a/text()').extract()
      # 同上,p标签下的 文字内容 ‘text()'
      item['desc'] = site.xpath('p[@class="post_item_summary"]/text()').extract()
      items.append(item)
    return items
Copy after login

(4)运行,

scrapy crawl blog # 即可
Copy after login

(5)输出文件。

在 settings.py 中进行输出配置。

# 输出文件位置
FEED_URI = 'blog.xml'
# 输出文件格式 可以为 json,xml,csv
FEED_FORMAT = 'xml'
Copy after login

输出位置为项目根文件夹下。

二、基本的 -- scrapy.spider.Spider

(1)使用交互shell

dizzy@dizzy-pc:~$ scrapy shell "http://www.baidu.com/"
Copy after login

2014-08-21 04:09:11+0800 [scrapy] INFO: Scrapy 0.24.4 started (bot: scrapybot)
2014-08-21 04:09:11+0800 [scrapy] INFO: Optional features available: ssl, http11, django
2014-08-21 04:09:11+0800 [scrapy] INFO: Overridden settings: {'LOGSTATS_INTERVAL': 0}
2014-08-21 04:09:11+0800 [scrapy] INFO: Enabled extensions: TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState
2014-08-21 04:09:11+0800 [scrapy] INFO: Enabled downloader middlewares: HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2014-08-21 04:09:11+0800 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2014-08-21 04:09:11+0800 [scrapy] INFO: Enabled item pipelines: 
2014-08-21 04:09:11+0800 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6024
2014-08-21 04:09:11+0800 [scrapy] DEBUG: Web service listening on 127.0.0.1:6081
2014-08-21 04:09:11+0800 [default] INFO: Spider opened
2014-08-21 04:09:12+0800 [default] DEBUG: Crawled (200) <GET http://www.baidu.com/> (referer: None)
[s] Available Scrapy objects:
[s]  crawler  <scrapy.crawler.Crawler object at 0xa483cec>
[s]  item    {}
[s]  request  <GET http://www.baidu.com/>
[s]  response  <200 http://www.baidu.com/>
[s]  settings  <scrapy.settings.Settings object at 0xa0de78c>
[s]  spider   <Spider 'default' at 0xa78086c>
[s] Useful shortcuts:
[s]  shelp()      Shell help (print this help)
[s]  fetch(req_or_url) Fetch request (or URL) and update local objects
[s]  view(response)  View response in a browser
 
>>> 
  # response.body 返回的所有内容
  # response.xpath('//ul/li') 可以测试所有的xpath内容
    More important, if you type response.selector you will access a selector object you can use to
query the response, and convenient shortcuts like response.xpath() and response.css() mapping to
response.selector.xpath() and response.selector.css()

Copy after login

也就是可以很方便的,以交互的形式来查看xpath选择是否正确。之前是用FireFox的F12来选择的,但是并不能保证每次都能正确的选择出内容。

也可使用:

scrapy shell 'http://scrapy.org' --nolog
# 参数 --nolog 没有日志
Copy after login

(2)示例

from scrapy import Spider
from scrapy_test.items import DmozItem
 
 
class DmozSpider(Spider):
  name = 'dmoz'
  allowed_domains = ['dmoz.org']
  start_urls = ['http://www.dmoz.org/Computers/Programming/Languages/Python/Books/',
         'http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/,'
         '']
 
  def parse(self, response):
    for sel in response.xpath('//ul/li'):
      item = DmozItem()
      item['title'] = sel.xpath('a/text()').extract()
      item['link'] = sel.xpath('a/@href').extract()
      item['desc'] = sel.xpath('text()').extract()
      yield item
Copy after login

(3)保存文件

可以使用,保存文件。格式可以 json,xml,csv

scrapy crawl -o 'a.json' -t 'json'
Copy after login

(4)使用模板创建spider

scrapy genspider baidu baidu.com
 
# -*- coding: utf-8 -*-
import scrapy
 
 
class BaiduSpider(scrapy.Spider):
  name = "baidu"
  allowed_domains = ["baidu.com"]
  start_urls = (
    'http://www.baidu.com/',
  )
 
  def parse(self, response):
    pass
Copy after login

这段先这样吧,记得之前5个的,现在只能想起4个来了. :-(

千万记得随手点下保存按钮。否则很是影响心情的(⊙o⊙)!

三、高级 -- scrapy.contrib.spiders.CrawlSpider

例子

#coding=utf-8
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
import scrapy
 
 
class TestSpider(CrawlSpider):
  name = 'test'
  allowed_domains = ['example.com']
  start_urls = ['http://www.example.com/']
  rules = (
    # 元组
    Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),
    Rule(LinkExtractor(allow=('item\.php', )), callback='pars_item'),
  )
 
  def parse_item(self, response):
    self.log('item page : %s' % response.url)
    item = scrapy.Item()
    item['id'] = response.xpath('//td[@id="item_id"]/text()').re('ID:(\d+)')
    item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()
    item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()
    return item
Copy after login

其他的还有 XMLFeedSpider

  • class scrapy.contrib.spiders.XMLFeedSpider
  • class scrapy.contrib.spiders.CSVFeedSpider
  • class scrapy.contrib.spiders.SitemapSpider

四、选择器

  >>> from scrapy.selector import Selector
  >>> from scrapy.http import HtmlResponse
Copy after login

可以灵活的使用 .css() 和 .xpath() 来快速的选取目标数据

关于选择器,需要好好研究一下。xpath() 和 css() ,还要继续熟悉 正则.

当通过class来进行选择的时候,尽量使用 css() 来选择,然后再用 xpath() 来选择元素的熟悉

五、Item Pipeline

Typical use for item pipelines are:
• cleansing HTML data # 清除HTML数据
• validating scraped data (checking that the items contain certain fields) # 验证数据
• checking for duplicates (and dropping them) # 检查重复
• storing the scraped item in a database # 存入数据库
(1)验证数据

from scrapy.exceptions import DropItem
 
class PricePipeline(object):
  vat_factor = 1.5
  def process_item(self, item, spider):
    if item['price']:
      if item['price_excludes_vat']:
        item['price'] *= self.vat_factor
    else:
      raise DropItem('Missing price in %s' % item)
Copy after login

(2)写Json文件

import json
 
class JsonWriterPipeline(object):
  def __init__(self):
    self.file = open('json.jl', 'wb')
  def process_item(self, item, spider):
    line = json.dumps(dict(item)) + '\n'
    self.file.write(line)
    return item
Copy after login

(3)检查重复

from scrapy.exceptions import DropItem
 
class Duplicates(object):
  def __init__(self):
    self.ids_seen = set()
  def process_item(self, item, spider):
    if item['id'] in self.ids_seen:
      raise DropItem('Duplicate item found : %s' % item)
    else:
      self.ids_seen.add(item['id'])
      return item
Copy after login

    至于将数据写入数据库,应该也很简单。在 process_item 函数中,将 item 存入进去即可了。

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles