最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python大數(shù)據(jù)之從網(wǎng)頁上爬取數(shù)據(jù)的方法詳解

 更新時(shí)間:2019年11月16日 10:43:42   作者:xuehyunyu  
這篇文章主要介紹了Python大數(shù)據(jù)之從網(wǎng)頁上爬取數(shù)據(jù)的方法,結(jié)合實(shí)例形式詳細(xì)分析了Python爬蟲爬取網(wǎng)頁數(shù)據(jù)的相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Python大數(shù)據(jù)之從網(wǎng)頁上爬取數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:

myspider.py  :

#!/usr/bin/python
# -*- coding:utf-8 -*-
from scrapy.spiders import Spider
from lxml import etree
from jredu.items import JreduItem
class JreduSpider(Spider):
  name = 'tt' #爬蟲的名字,必須的,唯一的
  allowed_domains = ['sohu.com']
  start_urls = [
    'http://www.sohu.com'
  ]
  def parse(self, response):
    content = response.body.decode('utf-8')
    dom = etree.HTML(content)
    for ul in dom.xpath("http://div[@class='focus-news-box']/div[@class='list16']/ul"):
      lis = ul.xpath("./li")
      for li in lis:
        item = JreduItem() #定義對象
        if ul.index(li) == 0:
          strong = li.xpath("./a/strong/text()")
          li.xpath("./a/@href")
          item['title']= strong[0]
          item['href'] = li.xpath("./a/@href")[0]
        else:
          la = li.xpath("./a[last()]/text()")
          item['title'] = la[0]
          item['href'] = li.xpath("./a[last()]/href")[0]
        yield item

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
import scrapy
class JreduItem(scrapy.Item):#相當(dāng)于Java里的實(shí)體類
  # define the fields for your item here like:
  # name = scrapy.Field()
  title = scrapy.Field()#創(chuàng)建一個(gè)field對象
  href = scrapy.Field()
  pass

middlewares.py  :

# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class JreduSpiderMiddleware(object):
  # Not all methods need to be defined. If a method is not defined,
  # scrapy acts as if the spider middleware does not modify the
  # passed objects.
  @classmethod
  def from_crawler(cls, crawler):
    # This method is used by Scrapy to create your spiders.
    s = cls()
    crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
    return s
  def process_spider_input(self, response, spider):
    # Called for each response that goes through the spider
    # middleware and into the spider.
    # Should return None or raise an exception.
    return None
  def process_spider_output(self, response, result, spider):
    # Called with the results returned from the Spider, after
    # it has processed the response.
    # Must return an iterable of Request, dict or Item objects.
    for i in result:
      yield i
  def process_spider_exception(self, response, exception, spider):
    # Called when a spider or process_spider_input() method
    # (from other spider middleware) raises an exception.
    # Should return either None or an iterable of Response, dict
    # or Item objects.
    pass
  def process_start_requests(self, start_requests, spider):
    # Called with the start requests of the spider, and works
    # similarly to the process_spider_output() method, except
    # that it doesn't have a response associated.
    # Must return only requests (not items).
    for r in start_requests:
      yield r
  def spider_opened(self, spider):
    spider.logger.info('Spider opened: %s' % spider.name)

pipelines.py  :

# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import codecs
import json
class JreduPipeline(object):
  def __init__(self):
    self.fill = codecs.open("data.txt",encoding="utf-8",mode="wb");
  def process_item(self, item, spider):
    line = json.dumps(dict(item))+"\n"
    self.fill.write(line)
    return item

settings.py   :

# -*- coding: utf-8 -*-
# Scrapy settings for jredu project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#   http://doc.scrapy.org/en/latest/topics/settings.html
#   http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#   http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'jredu'
SPIDER_MODULES = ['jredu.spiders']
NEWSPIDER_MODULE = 'jredu.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'jredu (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# 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',
#}
# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#  'jredu.middlewares.JreduSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#  'jredu.middlewares.MyCustomDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#  'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
  'jredu.pipelines.JreduPipeline': 300,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.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 http://scrapy.readthedocs.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'

最后需要一個(gè)程序入口的方法:

main.py     :

#!/usr/bin/python
# -*- coding:utf-8 -*-
#爬蟲文件的執(zhí)行入口
from scrapy import cmdline
cmdline.execute("scrapy crawl tt".split())

更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python正則表達(dá)式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • 詳解Python的文件處理

    詳解Python的文件處理

    這篇文章主要為大家介紹了Python的文件處理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-12-12
  • Python裝飾器使用實(shí)例:驗(yàn)證參數(shù)合法性

    Python裝飾器使用實(shí)例:驗(yàn)證參數(shù)合法性

    這篇文章主要介紹了Python裝飾器使用實(shí)例:驗(yàn)證參數(shù)合法性,本文直接給出代碼實(shí)例,代碼中包含詳細(xì)注釋,需要的朋友可以參考下
    2015-06-06
  • 詳解python中g(shù)roupby函數(shù)通俗易懂

    詳解python中g(shù)roupby函數(shù)通俗易懂

    這篇文章主要介紹了詳解python中g(shù)roupby函數(shù)通俗易懂,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • 基于Python+PyQt5+Pandas編寫的帶圖形界面的Excel合并工具

    基于Python+PyQt5+Pandas編寫的帶圖形界面的Excel合并工具

    在日常辦公或數(shù)據(jù)處理中,經(jīng)常會遇到多個(gè) Excel 文件需要合并的場景,手工復(fù)制不僅效率低,而且容易出錯(cuò),本文將手把手教你使用 Python + PyQt5 + Pandas 編寫一個(gè)帶圖形界面的 Excel 合并工具,需要的朋友可以參考下
    2026-01-01
  • 使用Spire.XLS for Python高效讀取Excel數(shù)據(jù)的代碼實(shí)現(xiàn)

    使用Spire.XLS for Python高效讀取Excel數(shù)據(jù)的代碼實(shí)現(xiàn)

    在數(shù)據(jù)驅(qū)動的時(shí)代,Python已成為數(shù)據(jù)處理領(lǐng)域的瑞士軍刀,然而,當(dāng)我們面對最常見的數(shù)據(jù)載體——Excel文件時(shí),如何高效、準(zhǔn)確地從中提取所需信息,卻常常成為許多開發(fā)者和數(shù)據(jù)分析師的痛點(diǎn),本文給大家介紹了如何使用Spire.XLS for Python高效讀取Excel數(shù)據(jù)
    2025-09-09
  • Python中的上下文管理器相關(guān)知識詳解

    Python中的上下文管理器相關(guān)知識詳解

    這篇文章主要介紹了Python中的上下文管理器相關(guān)知識詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • 使用ChatGPT進(jìn)行Abaqus二次開發(fā)詳解

    使用ChatGPT進(jìn)行Abaqus二次開發(fā)詳解

    這篇文章主要為大家介紹了使用ChatGPT進(jìn)行Abaqus二次開發(fā)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-03-03
  • Python 等分切分?jǐn)?shù)據(jù)及規(guī)則命名的實(shí)例代碼

    Python 等分切分?jǐn)?shù)據(jù)及規(guī)則命名的實(shí)例代碼

    這篇文章主要介紹了Python 等分切分?jǐn)?shù)據(jù)及規(guī)則命名的實(shí)例代碼,代碼簡單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-08-08
  • Django實(shí)現(xiàn)內(nèi)容緩存實(shí)例方法

    Django實(shí)現(xiàn)內(nèi)容緩存實(shí)例方法

    在本篇文章里小編給大家整理了關(guān)于Django實(shí)現(xiàn)內(nèi)容緩存實(shí)例方法,有需要的朋友們可以跟著學(xué)習(xí)下。
    2020-06-06
  • Python3內(nèi)置模塊之base64編解碼方法詳解

    Python3內(nèi)置模塊之base64編解碼方法詳解

    這篇文章主要介紹了Python3內(nèi)置模塊之base64編解碼方法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07

最新評論

建德市| 沐川县| 成武县| 修水县| 凌云县| 南郑县| 新晃| 延安市| 高台县| 博湖县| 大足县| 明星| 绥化市| 崇州市| 东海县| 清远市| 红原县| 新干县| 广德县| 英德市| 康平县| 麟游县| 科尔| 长武县| 漯河市| 平乡县| 九龙县| 抚顺县| 周宁县| 夏邑县| 永仁县| 鸡泽县| 普格县| 于田县| 慈溪市| 石楼县| 仙桃市| 循化| 东宁县| 神池县| 从化市|