日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

[簡單的python爬蟲實戰(zhàn)] 獲取1688網(wǎng)頁上的商品信息

 huowufenghuang 2019-05-16

語言:python 3.6 / 框架: Scrapy 1.5 /  數(shù)據(jù)庫:Mysql 8.0 / IDE: pycharm

1. 生成項目

首先,安裝好基本的軟件。之后到項目文件夾處 按住 shift+右鍵,打開命令行模式。

執(zhí)行 scrapy startproject [項目名] 生成項目文件。cd [項目名] 進入到項目文件夾中后執(zhí)行 scrapy genspider <爬蟲名> <domain/域名(起始頁)> 生成爬蟲文件。

2. 創(chuàng)建數(shù)據(jù)對象 items.py。在mysql中建立對應的數(shù)據(jù)表單。(注意表的字符編碼,這里設置的數(shù)據(jù)編碼是CHARACTER SET utf8 COLLATE utf8_general_ci)

class A1688Item_selloffer(scrapy.Item):
    title = scrapy.Field()     #標題
    company = scrapy.Field()   #公司
    price = scrapy.Field()     #售價
    sell = scrapy.Field()      #30天成交量
    method = scrapy.Field()    #銷售模式
    rebuy = scrapy.Field()     #回頭率
    address = scrapy.Field()   #地址
    subicon = scrapy.Field()   #服務保障

3.編寫爬蟲邏輯

import scrapy
from bs4 import BeautifulSoup
from A1688.items import A1688Item_selloffer #導入item類

KEYWORD="關(guān)鍵詞"
PAGE='1'

class A1688SellofferSpider(scrapy.Spider):
    name = 'A1688-selloffer'
    # allowed_domains = ['www.1688.com']     #爬蟲允許爬取的網(wǎng)址域名。
    # start_urls = ['https://www.1688.com/'] #需要爬取的鏈接的列表,response對象默認傳遞給 self.parse 函數(shù)處理。
    def start_requests(self):
        for page in range(1, int(PAGE)+1):
            url = 'https://s.1688.com/selloffer/offer_search.htm?keywords=%s&beginPage=%s' % (KEYWORD, page)
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        #實例化一個數(shù)據(jù)模型        
        item = A1688Item_selloffer()
        for tag in response.css('.sw-dpl-offer-item').extract():
            try:
                # 從response中利用css選擇器提取出來的標簽是文本形式,需要利用 BeautifulSoup 轉(zhuǎn)換成BeautifulSoup.Tag 對象進行進一步提取。
                soup = BeautifulSoup(tag, 'lxml')

                item['title'] = soup.select(".sw-dpl-offer-photo img")[0].attrs['alt']
                item['company'] = soup.select(".sw-dpl-offer-companyName")[0].attrs['title']
                item['price'] = soup.select(".sw-dpl-offer-priceNum")[0].attrs['title']
                item['sell'] = soup.select(".sm-offer-tradeBt")[0].attrs['title']
                item['rebuy'] =soup.select(".sm-widget-offershopwindowshoprepurchaserate span")[2].string
                item['method']  = soup.select(".sm-widget-offershopwindowshoprepurchaserate i")[0].string
                #對于不一定能獲取的數(shù)據(jù),需要判斷數(shù)據(jù)存在與否。
                if soup.select(".sm-offer-location")[0].attrs['title']:
                    address= soup.select(".sm-offer-location")[0].attrs['title']
                else:
                    address = " "
                item['address'] =address

                if soup.select(".sm-offer-subicon a"):
                    subicon = []
                    for i in soup.select(".sm-offer-subicon a"):
                        subicon.append(i.attrs['title'] + ',')
                    print(subicon)
                    item['subicon']=subicon
                else:
                    item['subicon'] = ' '
                #返回這個數(shù)據(jù)模型,交給 ITEM_PIPELINES 處理
                yield item
            except Exception as error:
                yield item
                print("出錯了:", error)
                continue

4.建立數(shù)據(jù)管道

#連接數(shù)據(jù)庫,獲取cursor以便之后對數(shù)據(jù)就行增刪查改
import pymysql
from A1688 import settings

# 創(chuàng)建DBPipeline類,在其中進行對數(shù)據(jù)庫的操作。
class DBPipeline(object):
    def __init__(self):
        # 連接數(shù)據(jù)庫??梢栽趕ettings中對數(shù)據(jù)庫連接需要的參數(shù)進行設置
        self.connect = pymysql.connect(
            host=settings.MYSQL_HOST,
            port=settings.MYSQL_PORT,
            db=settings.MYSQL_DBNAME,
            user=settings.MYSQL_USER,
            passwd=settings.MYSQL_PASSWD,
            charset='utf8', #注意這里charset屬性為 ‘utf8’,中間沒有-,是因為數(shù)據(jù)庫中的字符名稱就是'utf8'
            use_unicode=True)

        # 創(chuàng)建數(shù)據(jù)庫游標對象,通過cursor對象對數(shù)據(jù)庫執(zhí)行增刪查改
        self.cursor = self.connect.cursor()
        print("數(shù)據(jù)庫鏈接成功mysql connect succes")
        
    #重載方法process_item(self, item, spider):
    #返回一個具有數(shù)據(jù)的dict,或者item對象,或者拋出DropItem異常,被丟棄的item將不會被之后的pipeline組件所處理
    #利用這個方法,可以對item采集的數(shù)據(jù)進行增刪查改,利用cursor執(zhí)行sql語句,然后使用self.connect.commit()提交sql語句
    def process_item(self, item, spider):
        try:
            # 插入數(shù)據(jù)。利用execute()方法執(zhí)行sql語句對數(shù)據(jù)庫進行操作。這里執(zhí)行的是寫入語句 "insert into 表名(列名) value (數(shù)據(jù))"
            # 需要注意的是。需要注意的是數(shù)據(jù)庫的編碼格式,以及sql語句的使用規(guī)范。(如varchar 類型的數(shù)據(jù)接收的是字符串,要帶'')
            self.cursor.execute(
                "insert into a1688item_selloffer (title,company,price,sell,method,rebuy,address,subicon) value (%s,%s,%s,%s,%s,%s,%s,%s)"
                [item['title'],item['company'],item['price'],item['sell'],item['method'],item['rebuy'],item['address'],item['subicon']]
            )
            print("insert success")
            # 提交sql語句
            self.connect.commit()
        except Exception as error:
            # 出現(xiàn)錯誤時打印錯誤日志
            print('Insert error:', error)
        return item
5.修改settings
# 修改USER_AGENT,讓服務器識別爬蟲為瀏覽器
USER_AGENT =  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"

#設置爬蟲執(zhí)行過程中使用的數(shù)據(jù)處理管道
ITEM_PIPELINES = {
    'A1688.pipelines.DBPipeline': 300, #這個數(shù)的范圍是0-1000,這個數(shù)值確定了pipelines的運行順序,數(shù)字越小越優(yōu)先
}

# 設置與數(shù)據(jù)庫連接相關(guān)的變量
MYSQL_HOST = 'localhost' # 主機域名,默認為本地鏈接
MYSQL_PORT = 3306        # 數(shù)據(jù)庫端口,mysql一般默認用3306
MYSQL_DBNAME = 'a1688'   # 數(shù)據(jù)庫名字
MYSQL_USER = 'root'      # 用戶名
MYSQL_PASSWD = '******'  # 用戶密碼

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多