怎么在Python中使用Scrapy爬蟲(chóng)框架-創(chuàng)新互聯(lián)

怎么在Python中使用Scrapy爬蟲(chóng)框架?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。

創(chuàng)新互聯(lián)2013年至今,先為政和等服務(wù)建站,政和等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢(xún)服務(wù)。為政和企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。一、創(chuàng)建Scrapy項(xiàng)目

scrapy startproject Tencent

命令執(zhí)行后,會(huì)創(chuàng)建一個(gè)Tencent文件夾,結(jié)構(gòu)如下

二、編寫(xiě)item文件,根據(jù)需要爬取的內(nèi)容定義爬取字段
# -*- coding: utf-8 -*-
import scrapy
class TencentItem(scrapy.Item):
  # 職位名
  positionname = scrapy.Field()
  # 詳情連接
  positionlink = scrapy.Field()
  # 職位類(lèi)別
  positionType = scrapy.Field()
  # 招聘人數(shù)
  peopleNum = scrapy.Field()
  # 工作地點(diǎn)
  workLocation = scrapy.Field()
  # 發(fā)布時(shí)間
  publishTime = scrapy.Field()

三、編寫(xiě)spider文件

進(jìn)入Tencent目錄,使用命令創(chuàng)建一個(gè)基礎(chǔ)爬蟲(chóng)類(lèi):

# tencentPostion為爬蟲(chóng)名,tencent.com為爬蟲(chóng)作用范圍
scrapy genspider tencentPostion "tencent.com"

執(zhí)行命令后會(huì)在spiders文件夾中創(chuàng)建一個(gè)tencentPostion.py的文件,現(xiàn)在開(kāi)始對(duì)其編寫(xiě):

# -*- coding: utf-8 -*-
import scrapy
from tencent.items import TencentItem
class TencentpositionSpider(scrapy.Spider):
  """
  功能:爬取騰訊社招信息
  """
  # 爬蟲(chóng)名
  name = "tencentPosition"
  # 爬蟲(chóng)作用范圍
  allowed_domains = ["tencent.com"]
  url = "http://hr.tencent.com/position.php?&start="
  offset = 0
  # 起始url
  start_urls = [url + str(offset)]
  def parse(self, response):
    for each in response.xpath("//tr[@class='even'] | //tr[@class='odd']"):
      # 初始化模型對(duì)象
      item = TencentItem()
      # 職位名稱(chēng)
      item['positionname'] = each.xpath("./td[1]/a/text()").extract()[0]
      # 詳情連接
      item['positionlink'] = each.xpath("./td[1]/a/@href").extract()[0]
      # 職位類(lèi)別
      item['positionType'] = each.xpath("./td[2]/text()").extract()[0]
      # 招聘人數(shù)
      item['peopleNum'] = each.xpath("./td[3]/text()").extract()[0]
      # 工作地點(diǎn)
      item['workLocation'] = each.xpath("./td[4]/text()").extract()[0]
      # 發(fā)布時(shí)間
      item['publishTime'] = each.xpath("./td[5]/text()").extract()[0]
      yield item
    if self.offset < 1680:
      self.offset += 10
    # 每次處理完一頁(yè)的數(shù)據(jù)之后,重新發(fā)送下一頁(yè)頁(yè)面請(qǐng)求
    # self.offset自增10,同時(shí)拼接為新的url,并調(diào)用回調(diào)函數(shù)self.parse處理Response
    yield scrapy.Request(self.url + str(self.offset), callback = self.parse)

四、編寫(xiě)pipelines文件

# -*- coding: utf-8 -*-
import json
class TencentPipeline(object):
  """ 
    功能:保存item數(shù)據(jù) 
  """
  def __init__(self):
    self.filename = open("tencent.json", "w")
  def process_item(self, item, spider):
    text = json.dumps(dict(item), ensure_ascii = False) + ",\n"
    self.filename.write(text.encode("utf-8"))
    return item
  def close_spider(self, spider):
    self.filename.close()

五、settings文件設(shè)置(主要設(shè)置內(nèi)容)

# 設(shè)置請(qǐng)求頭部,添加url
DEFAULT_REQUEST_HEADERS = {
  "User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;",
  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}
# 設(shè)置item——pipelines
ITEM_PIPELINES = {
  'tencent.pipelines.TencentPipeline': 300,
}

執(zhí)行命令,運(yùn)行程序

# tencentPosition為爬蟲(chóng)名
scrapy crwal tencentPosition

使用CrawlSpider類(lèi)改寫(xiě)

# 創(chuàng)建項(xiàng)目
scrapy startproject TencentSpider
# 進(jìn)入項(xiàng)目目錄下,創(chuàng)建爬蟲(chóng)文件
scrapy genspider -t crawl tencent tencent.com
item等文件寫(xiě)法不變,主要是爬蟲(chóng)文件的編寫(xiě)
# -*- coding:utf-8 -*-
import scrapy
# 導(dǎo)入CrawlSpider類(lèi)和Rule
from scrapy.spiders import CrawlSpider, Rule
# 導(dǎo)入鏈接規(guī)則匹配類(lèi),用來(lái)提取符合規(guī)則的連接
from scrapy.linkextractors import LinkExtractor
from TencentSpider.items import TencentItem
class TencentSpider(CrawlSpider):
  name = "tencent"
  allow_domains = ["hr.tencent.com"]
  start_urls = ["http://hr.tencent.com/position.php?&start=0#a"]
  # Response里鏈接的提取規(guī)則,返回的符合匹配規(guī)則的鏈接匹配對(duì)象的列表
  pagelink = LinkExtractor(allow=("start=\d+"))
  rules = [
    # 獲取這個(gè)列表里的鏈接,依次發(fā)送請(qǐng)求,并且繼續(xù)跟進(jìn),調(diào)用指定回調(diào)函數(shù)處理
    Rule(pagelink, callback = "parseTencent", follow = True)
  ]
  # 指定的回調(diào)函數(shù)
  def parseTencent(self, response):
    for each in response.xpath("//tr[@class='even'] | //tr[@class='odd']"):
      item = TencentItem()
      # 職位名稱(chēng)
      item['positionname'] = each.xpath("./td[1]/a/text()").extract()[0]
      # 詳情連接
      item['positionlink'] = each.xpath("./td[1]/a/@href").extract()[0]
      # 職位類(lèi)別
      item['positionType'] = each.xpath("./td[2]/text()").extract()[0]
      # 招聘人數(shù)
      item['peopleNum'] = each.xpath("./td[3]/text()").extract()[0]
      # 工作地點(diǎn)
      item['workLocation'] = each.xpath("./td[4]/text()").extract()[0]
      # 發(fā)布時(shí)間
      item['publishTime'] = each.xpath("./td[5]/text()").extract()[0]
      yield item

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。

當(dāng)前名稱(chēng):怎么在Python中使用Scrapy爬蟲(chóng)框架-創(chuàng)新互聯(lián)
文章出自:http://muchs.cn/article10/cdgcdo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、網(wǎng)站制作、微信小程序網(wǎng)站內(nèi)鏈響應(yīng)式網(wǎng)站、Google

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)