日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

用 Python 爬虫框架 Scrapy 爬取心目中的女神

發布時間:2024/7/23 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用 Python 爬虫框架 Scrapy 爬取心目中的女神 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

From :http://www.cnblogs.com/wanghzh/p/5824181.html

?

本博文將帶領你從入門到精通爬蟲框架 Scrapy,最終具備爬取任何網頁的數據的能力。
本文以校花網為例進行爬取,校花網:http://www.xiaohuar.com?讓你體驗爬取校花的成就感。

?

Scrapy,Python開發的一個快速,高層次的屏幕抓取和web抓取框架,用于抓取web站點并從頁面中提取結構化的數據。Scrapy用途廣泛,可以用于數據挖掘、監測和自動化測試。

Scrapy吸引人的地方在于它是一個框架,任何人都可以根據需求方便的修改。它也提供了多種類型爬蟲的基類,如BaseSpider、sitemap爬蟲等,最新版本又提供了web2.0爬蟲的支持。

Scratch,是抓取的意思,這個Python的爬蟲框架叫Scrapy,大概也是這個意思吧,就叫它:小刮刮吧。

?

Scrapy 使用了 Twisted異步網絡庫來處理網絡通訊。整體架構大致如下:

?

Scrapy主要包括了以下組件:

  • 引擎(Scrapy)
    用來處理整個系統的數據流處理, 觸發事務(框架核心)
  • 調度器(Scheduler)
    用來接受引擎發過來的請求, 壓入隊列中, 并在引擎再次請求的時候返回. 可以想像成一個URL(抓取網頁的網址或者說是鏈接)的優先隊列, 由它來決定下一個要抓取的網址是什么, 同時去除重復的網址
  • 下載器(Downloader)
    用于下載網頁內容, 并將網頁內容返回給蜘蛛(Scrapy下載器是建立在twisted這個高效的異步模型上的)
  • 爬蟲(Spiders)
    爬蟲是主要干活的, 用于從特定的網頁中提取自己需要的信息, 即所謂的實體(Item)。用戶也可以從中提取出鏈接,讓Scrapy繼續抓取下一個頁面
  • 項目管道(Pipeline)
    負責處理爬蟲從網頁中抽取的實體,主要的功能是持久化實體、驗證實體的有效性、清除不需要的信息。當頁面被爬蟲解析后,將被發送到項目管道,并經過幾個特定的次序處理數據。
  • 下載器中間件(Downloader Middlewares)
    位于Scrapy引擎和下載器之間的框架,主要是處理Scrapy引擎與下載器之間的請求及響應。
  • 爬蟲中間件(Spider Middlewares)
    介于Scrapy引擎和爬蟲之間的框架,主要工作是處理蜘蛛的響應輸入和請求輸出。
  • 調度中間件(Scheduler Middewares)
    介于Scrapy引擎和調度之間的中間件,從Scrapy引擎發送到調度的請求和響應。

?

Scrapy運行流程大概如下:

  • 引擎從調度器中取出一個鏈接(URL)用于接下來的抓取
  • 引擎把URL封裝成一個請求(Request)傳給下載器
  • 下載器把資源下載下來,并封裝成應答包(Response)
  • 爬蟲解析Response
  • 解析出實體(Item),則交給實體管道進行進一步的處理
  • 解析出的是鏈接(URL),則把URL交給調度器等待抓取
  • ?

    ?

    一、安裝

      因為python3并不能完全支持Scrapy,因此為了完美運行Scrapy,我們使用python2.7來編寫和運行Scrapy。

    pip install Scrapy

    注:windows平臺需要依賴 pywin32,請根據自己系統32/64位選擇下載安裝,https://sourceforge.net/projects/pywin32/
    其它可能依賴的安裝包:lxml-3.6.4-cp27-cp27m-win_amd64.whl,VCForPython27.msi百度下載即可

    ?

    ?

    二、基本使用

    ?

    1. 創建項目

    ? ? ? ? 運行命令:scrapy startproject p1(your_project_name)

    2. 自動創建目錄的結果:

    ? ? ? ? 文件說明:

    • scrapy.cfg : 項目的配置信息,主要為Scrapy命令行工具提供一個基礎的配置信息。
      ? ? ? ? ? ? ? ? ? ? ? 真正爬蟲相關的配置信息在settings.py文件中。
    • items.py? :? ?設置數據存儲模板,用于結構化數據,如:Django的Model
    • pipelines :? ? 數據處理行為,如:一般結構化的數據持久化
    • settings.py : 配置文件,如:遞歸的層數、并發數,延遲下載等
    • spiders? ? ? ?: 爬蟲目錄,如:創建文件,編寫爬蟲規則

    ? ? ? ? 注意:一般創建爬蟲文件時,以網站域名命名

    3. 編寫爬蟲

    ? ? ? ? 在spiders目錄中新建 xiaohuar_spider.py 文件

    示例代碼:

    #!/usr/bin/python3 # -*- coding: utf-8 -*- # @Author : # @File : test.py # @Software : PyCharm # @description : XXXimport scrapyclass XiaoHuarSpider(scrapy.spiders.Spider):name = "xiaohuar"allowed_domains = ["xiaohuar.com"]start_urls = ["http://www.xiaohuar.com/hua/",] def parse(self, response):# print(response, type(response))# from scrapy.http.response.html import HtmlResponse# print(response.body_as_unicode())current_url = response.url # 爬取時請求的urlbody = response.body # 返回的htmlunicode_body = response.body_as_unicode() # 返回的html unicode編碼print(current_url)print(body)print(unicode_body)def test_1():from scrapy import cmdlinecmdline.execute('scrapy crawl xiaohuar'.split())def test_2():from scrapy.crawler import CrawlerProcessfrom scrapy.utils.project import get_project_settingsprocess = CrawlerProcess(get_project_settings())process.crawl('xiaohuar')process.start()if __name__ == '__main__':test_1()# test_2()pass

    備注:

    • 1.爬蟲文件需要定義一個類,并繼承 scrapy.spiders.Spider
    • 2.必須定義 name,即爬蟲名,如果沒有 name,會報錯。因為源碼中是這樣定義的:

    • 3.編寫函數parse,這里需要注意的是,該函數名不能改變,因為Scrapy源碼中默認callback函數的函數名就是parse;
    • 4.定義需要爬取的url,放在列表中,因為可以爬取多個url,Scrapy源碼是一個For循環,從上到下爬取這些url,使用生成器迭代將url發送給下載器下載url的html。源碼截圖:

    ?

    4、運行

    ? ? ? ? 進入p1目錄,運行命令:scrapy crawl xiaohau --nolog
    ? ? ? ? 格式:scrapy crawl+爬蟲名 ?--nolog 即不顯示日志

    5.scrapy查詢語法:

      當我們爬取大量的網頁,如果自己寫正則匹配,會很麻煩,也很浪費時間,令人欣慰的是,scrapy內部支持更簡單的查詢語法,幫助我們去html中查詢我們需要的標簽和標簽內容以及標簽屬性。下面逐一進行介紹:

    • 查詢子子孫孫中的某個標簽(以div標簽為例)://div
    • 查詢兒子中的某個標簽(以div標簽為例):/div
    • 查詢標簽中帶有某個class屬性的標簽://div[@class='c1']即子子孫孫中標簽是div且class=‘c1’的標簽
    • 查詢標簽中帶有某個class=‘c1’并且自定義屬性name=‘alex’的標簽://div[@class='c1'][@name='alex']
    • 查詢某個標簽的文本內容://div/span/text() 即查詢子子孫孫中div下面的span標簽中的文本內容
    • 查詢某個屬性的值(例如查詢a標簽的href屬性)://a/@href

    示例代碼:

    #!/usr/bin/python3 # -*- coding: utf-8 -*- # @Author : # @File : test.py # @Software : PyCharm # @description : XXXimport scrapy import os import requests from lxml import etreeclass XiaoHuarSpider(scrapy.spiders.Spider):name = "xiaohuar"allowed_domains = ["xiaohuar.com"]start_urls = ["http://www.xiaohuar.com/hua/",]dont_proxy = True# 自定義配置。自定義配置會覆蓋項目級別(即setting.py)配置custom_settings = {'DEFAULT_REQUEST_HEADERS': {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8','Accept-Encoding': 'gzip, deflate','Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8','Connection': 'keep-alive','Host': 'www.xiaohuar.com','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ''AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'},# 'ITEM_PIPELINES': {# 'maoyan.pipelines.pipelines.MainPipelineKafka': 300,# # 'maoyan.pipelines.pipelines.MainPipelineSQLServer': 300,# },# 'DOWNLOADER_MIDDLEWARES': {# # 'maoyan.middlewares.useragent.RandomUserAgentMiddleware': 90,# # 'scrapy.downloadermiddlewares.retry.RetryMiddleware': 100,# # 'maoyan.middlewares.middlewares.ZhiMaIPMiddleware': 125,# 'maoyan.middlewares.proxy_middlewares.ProxyMiddleware': 125,# },# 'CONCURRENT_REQUESTS': 100,# 'DOWNLOAD_DELAY': 0.5,# 'RETRY_ENABLED': False,# 'RETRY_TIMES': 1,# 'RETRY_HTTP_CODES': [500, 503, 504, 400, 403, 404, 408],# 'REDIRECT_ENABLED': False, # 關掉重定向,不會重定向到新的地址# 'HTTPERROR_ALLOWED_CODES': [301, 302, 403], # 返回301, 302時,按正常返回對待,可以正常寫入cookie}def parse(self, response):current_url = response.urlprint(current_url)# 創建查詢的 xpath 對象 (也可以使用 scrapy 中 response 中 xpath)# selector = etree.HTML(response.text)div_xpath = '//div[@class="item_t"]'items = response.xpath(div_xpath)for item in items:# 圖片 地址# /d/file/20190117/07a7e6bc4639ded4972d0dc00bfc331b.jpgimg_src = item.xpath('.//img/@src').extract_first()img_url = 'http://www.xiaohuar.com{0}'.format(img_src) if 'https://' not in img_src else img_src# 校花 名字mm_name = item.xpath('.//span[@class="price"]/text()').extract_first()# 校花 學校mm_school = item.xpath('.//a[@class="img_album_btn"]/text()').extract_first()if not os.path.exists('./img/'):os.mkdir('./img')file_name = "%s_%s.jpg" % (mm_school, mm_name)file_path = os.path.join("./img", file_name)r = requests.get(img_url)if r.status_code == 200:with open(file_path, 'wb') as f:f.write(r.content)else:print('status code : {0}'.format(r.status_code))next_page_xpath = '//div[@class="page_num"]//a[contains(text(), "下一頁")]/@href'next_page_url = response.xpath(next_page_xpath).extract_first()if next_page_url:r_headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8','Accept-Encoding': 'gzip, deflate','Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8','Connection': 'keep-alive','Host': 'www.xiaohuar.com','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ''AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'}yield scrapy.Request(next_page_url, headers=r_headers, callback=self.parse)def test_1():from scrapy import cmdlinecmdline.execute('scrapy crawl xiaohuar'.split())def test_2():from scrapy.crawler import CrawlerProcessfrom scrapy.utils.project import get_project_settingsprocess = CrawlerProcess(get_project_settings())process.crawl('xiaohuar')process.start()if __name__ == '__main__':test_1()# test_2()pass

    運行結果截圖:

    ?

    5.遞歸爬取網頁

      上述代碼僅僅實現了一個url的爬取,如果該url的爬取的內容中包含了其他url,而我們也想對其進行爬取,那么如何實現遞歸爬取網頁呢?

    ?示例代碼:

    # 獲取所有的url,繼續訪問,并在其中尋找相同的urlall_urls = response.xpath('//a/@href').extract()for url in all_urls:if url.startswith('http://www.xiaohuar.com/list-1-'):yield Request(url, callback=self.parse)

    即通過yield生成器向每一個url發送request請求,并執行返回函數parse,從而遞歸獲取校花圖片和校花姓名學校等信息。

    注:可以修改settings.py 中的配置文件,以此來指定“遞歸”的層數,如:?DEPTH_LIMIT = 1

    ?

    6.scrapy查詢語法中的正則:

    可以使用 正則表達式匹配,也可以使用 xpath、css 選擇器。上面程序使用的 xpath 表達式來匹配需要的信息。

    更多 xpath 使用可以參看:http://www.runoob.com/xpath/xpath-tutorial.html

    xpath 高級用法

    ?

    示例代碼:

    # !/usr/bin/env python # -*- coding:utf-8 -*- # 選擇器規則 import scrapy import hashlib from tutorial.items import JinLuoSiItem from scrapy.http import Request from scrapy.selector import HtmlXPathSelectorclass JinLuoSiSpider(scrapy.spiders.Spider):count = 0url_set = set()name = "jluosi"domain = 'http://www.jluosi.com'allowed_domains = ["jluosi.com"]start_urls = ["http://www.jluosi.com:80/ec/goodsDetail.action?jls=QjRDNEIzMzAzOEZFNEE3NQ==",]def parse(self, response):md5_obj = hashlib.md5()md5_obj.update(response.url)md5_url = md5_obj.hexdigest()if md5_url in JinLuoSiSpider.url_set:passelse:JinLuoSiSpider.url_set.add(md5_url)hxs = HtmlXPathSelector(response)if response.url.startswith('http://www.jluosi.com:80/ec/goodsDetail.action'):item = JinLuoSiItem()item['company'] = hxs.select('//div[@class="ShopAddress"]/ul/li[1]/text()').extract()item['link'] = hxs.select('//div[@class="ShopAddress"]/ul/li[2]/text()').extract()item['qq'] = hxs.select('//div[@class="ShopAddress"]//a/@href').re('.*uin=(?P<qq>\d*)&')item['address'] = hxs.select('//div[@class="ShopAddress"]/ul/li[4]/text()').extract()item['title'] = hxs.select('//h1[@class="goodsDetail_goodsName"]/text()').extract()item['unit'] = hxs.select('//table[@class="R_WebDetail_content_tab"]//tr[1]//td[3]/text()').extract()product_list = []product_tr = hxs.select('//table[@class="R_WebDetail_content_tab"]//tr')for i in range(2, len(product_tr)):temp = {'standard':hxs.select('//table[@class="R_WebDetail_content_tab"]//tr[%d]//td[2]/text()' % i).extract()[0].strip(),'price':hxs.select('//table[@class="R_WebDetail_content_tab"]//tr[%d]//td[3]/text()' % i).extract()[0].strip(),}product_list.append(temp)item['product_list'] = product_listyield itemcurrent_page_urls = hxs.select('//a/@href').extract()for i in range(len(current_page_urls)):url = current_page_urls[i]if url.startswith('http://www.jluosi.com'):url_ab = urlyield Request(url_ab, callback=self.parse) def parse(self, response): #獲取響應cookiesfrom scrapy.http.cookies import CookieJarcookieJar = CookieJar()cookieJar.extract_cookies(response, response.request)print(cookieJar._cookies)

    更多選擇器規則:http://scrapy-chs.readthedocs.io/zh_CN/latest/topics/selectors.html

    ?

    7、格式化處理

      上述實例只是簡單的圖片處理,所以在parse方法中直接處理。如果對于想要獲取更多的數據(獲取頁面的價格、商品名稱、QQ等),則可以利用Scrapy的items將數據格式化,然后統一交由pipelines來處理。即不同功能用不同文件實現。

    ?items:即用戶需要爬取哪些數據,是用來格式化數據,并告訴pipelines哪些數據需要保存。

    示例 items.py文件:

    # -*- coding: utf-8 -*-# Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass JieYiCaiItem(scrapy.Item):company = scrapy.Field()title = scrapy.Field()qq = scrapy.Field()info = scrapy.Field()more = scrapy.Field()

    即:需要爬取所有 url 中的公司名,title,qq,基本信息info,更多信息more。

    上述定義模板,以后對于從請求的源碼中獲取的數據同樣按照此結構來獲取,所以在spider中需要有一下操作:

    #!/usr/bin/env python # -*- coding:utf-8 -*- # spider import scrapy import hashlib from beauty.items import JieYiCaiItem from scrapy.http import Request from scrapy.selector import HtmlXPathSelector from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractorclass JieYiCaiSpider(scrapy.spiders.Spider):count = 0url_set = set()name = "jieyicai"domain = 'http://www.jieyicai.com'allowed_domains = ["jieyicai.com"]start_urls = ["http://www.jieyicai.com",]rules = [#下面是符合規則的網址,但是不抓取內容,只是提取該頁的鏈接(這里網址是虛構的,實際使用時請替換)#Rule(SgmlLinkExtractor(allow=(r'http://test_url/test?page_index=\d+'))),#下面是符合規則的網址,提取內容,(這里網址是虛構的,實際使用時請替換)#Rule(LinkExtractor(allow=(r'http://www.jieyicai.com/Product/Detail.aspx?pid=\d+')), callback="parse"),]def parse(self, response):md5_obj = hashlib.md5()md5_obj.update(response.url)md5_url = md5_obj.hexdigest()if md5_url in JieYiCaiSpider.url_set:passelse:JieYiCaiSpider.url_set.add(md5_url)hxs = HtmlXPathSelector(response)if response.url.startswith('http://www.jieyicai.com/Product/Detail.aspx'):item = JieYiCaiItem()item['company'] = hxs.select('//span[@class="username g-fs-14"]/text()').extract()item['qq'] = hxs.select('//span[@class="g-left bor1qq"]/a/@href').re('.*uin=(?P<qq>\d*)&')item['info'] = hxs.select('//div[@class="padd20 bor1 comard"]/text()').extract()item['more'] = hxs.select('//li[@class="style4"]/a/@href').extract()item['title'] = hxs.select('//div[@class="g-left prodetail-text"]/h2/text()').extract()yield itemcurrent_page_urls = hxs.select('//a/@href').extract()for i in range(len(current_page_urls)):url = current_page_urls[i]if url.startswith('/'):url_ab = JieYiCaiSpider.domain + urlyield Request(url_ab, callback=self.parse)

    上述代碼中:對url進行md5加密的目的是避免url過長,也方便保存在緩存或數據庫中。

    此處代碼的關鍵在于:

    • 將獲取的數據封裝在了Item對象中
    • yield Item對象 (一旦parse中執行yield Item對象,則自動將該對象交個pipelines的類來處理)
    # -*- coding: utf-8 -*- # pipelines # 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.htmlimport json from twisted.enterprise import adbapi import MySQLdb.cursors import remobile_re = re.compile(r'(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}') phone_re = re.compile(r'(\d+-\d+|\d+)')class JsonPipeline(object):def __init__(self):self.file = open('/Users/wupeiqi/PycharmProjects/beauty/beauty/jieyicai.json', 'wb')def process_item(self, item, spider):line = "%s %s\n" % (item['company'][0].encode('utf-8'), item['title'][0].encode('utf-8'))self.file.write(line)return itemclass DBPipeline(object):def __init__(self):self.db_pool = adbapi.ConnectionPool('MySQLdb',db='DbCenter',user='root',passwd='123',cursorclass=MySQLdb.cursors.DictCursor,use_unicode=True)def process_item(self, item, spider):query = self.db_pool.runInteraction(self._conditional_insert, item)query.addErrback(self.handle_error)return itemdef _conditional_insert(self, tx, item):tx.execute("select nid from company where company = %s", (item['company'][0], ))result = tx.fetchone()if result:passelse:phone_obj = phone_re.search(item['info'][0].strip())phone = phone_obj.group() if phone_obj else ' 'mobile_obj = mobile_re.search(item['info'][1].strip())mobile = mobile_obj.group() if mobile_obj else ' 'values = (item['company'][0],item['qq'][0],phone,mobile,item['info'][2].strip(),item['more'][0])tx.execute("insert into company(company,qq,phone,mobile,address,more) values(%s,%s,%s,%s,%s,%s)", values)def handle_error(self, e):print 'error',e

    上述代碼中多個類的目的是,可以同時保存在文件和數據庫中,保存的優先級可以在配置文件settings中定義。

    ITEM_PIPELINES = {'beauty.pipelines.DBPipeline': 300,'beauty.pipelines.JsonPipeline': 100, } # 每行后面的整型值,確定了他們運行的順序,item按數字從低到高的順序,通過pipeline,通常將這些數字定義在0-1000范圍內。

    ?


    ?

    總結

    以上是生活随笔為你收集整理的用 Python 爬虫框架 Scrapy 爬取心目中的女神的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。