Python實(shí)戰(zhàn) - 第二周作業(yè)

代碼

  • 預(yù)處理部分 - 獲取頻道列表
# pre.py
from bs4 import BeautifulSoup
import requests


#
# 根據(jù)“全部分類(lèi)”頁(yè)面,找到所有的頻道入口
#
def parse_list():
    weburl = 'http://bj.ganji.com/wu/'
    web_data = requests.get(weburl)
    soup = BeautifulSoup(web_data.text, 'lxml', from_encoding="utf-8")
    suburllist = soup.select('#wrapper > div.content > div > div > dl > dt > a')
    for suburl in suburllist:
        print('http://bj.ganji.com' + suburl.get('href'))

# 找到的頻道入口列表
category_list = '''
    http://bj.ganji.com/jiaju/
    http://bj.ganji.com/rirongbaihuo/
    http://bj.ganji.com/shouji/
    http://bj.ganji.com/shoujihaoma/
    http://bj.ganji.com/bangong/
    http://bj.ganji.com/nongyongpin/
    http://bj.ganji.com/jiadian/
    http://bj.ganji.com/ershoubijibendiannao/
    http://bj.ganji.com/ruanjiantushu/
    http://bj.ganji.com/yingyouyunfu/
    http://bj.ganji.com/diannao/
    http://bj.ganji.com/xianzhilipin/
    http://bj.ganji.com/fushixiaobaxuemao/
    http://bj.ganji.com/meironghuazhuang/
    http://bj.ganji.com/shuma/
    http://bj.ganji.com/laonianyongpin/
    http://bj.ganji.com/xuniwupin/
    http://bj.ganji.com/qitawupin/
    http://bj.ganji.com/ershoufree/
    http://bj.ganji.com/wupinjiaohuan/
'''

if __name__ == '__main__':
    parse_list()

  • 解析各頻道列表頁(yè)面,并將url入庫(kù)
# splider1.py
from bs4 import BeautifulSoup
from multiprocessing import Pool
import requests
import time
import pymongo
import pre

client = pymongo.MongoClient('localhost', 27017)
ganji = client['ganji']
t_urllist = ganji['t_urllist']


#
# 解析具體的一頁(yè)列表信息并入庫(kù)
#
def parse_list(url):
    web_data = requests.get(url)
    soup = BeautifulSoup(web_data.text, 'lxml')
    # “轉(zhuǎn)轉(zhuǎn)”列表頁(yè)面,并且還有數(shù)據(jù)
    if soup.find('table', 'tbimg'):
        titles = soup.select('#infolist > div.infocon > table > tbody > tr.zzinfo > td.t > a')
        for title in titles:
            t_urllist.insert_one({'title': title.get_text(), 'url': title.get('href'), 'type': 'zz', 'flag': False})
            # print('{} ==> {}'.format(title.get_text(), title.get('href')))
    # 趕集網(wǎng)自身列表頁(yè)面,并且還有數(shù)據(jù)
    elif soup.find('div', 'layoutlist') and soup.find('ul', 'pageLink clearfix'):
        titles = soup.select('#wrapper > div.leftBox > div.layoutlist > dl > dt > a')
        for title in titles:
            t_urllist.insert_one({'title': title.get('title'), 'url': title.get('href'), 'type': 'nm', 'flag': False})
            # print('{} ==> {}'.format(title.get('title'), title.get('href')))
    # 此頁(yè)無(wú)數(shù)據(jù)啦
    else:
        print('后面沒(méi)有啦 : ' + url)
        pass
        # Nothing !


#
# 逐頁(yè)將某頻道的列表信息解析入庫(kù)
#
def process(channel):
    for i in range(1, 100):
        # 第一頁(yè)特殊處理,因?yàn)橹苯悠唇印畂1’將會(huì)打開(kāi)第二頁(yè)而非第一頁(yè)
        if i == 1:
            parse_list(channel)
        else:
            parse_list('{}o{}/'.format(channel, str(i)))
        # time.sleep(2)


#
# 程序入口 : 采用多線(xiàn)程將多個(gè)頻道的列表信息解析入庫(kù)
#
if __name__ == '__main__':
    # process('http://bj.ganji.com/bangong/')
    pool = Pool()
    pool.map(process, pre.category_list.split())

  • 從數(shù)據(jù)庫(kù)獲取url解析各詳情頁(yè)面
# splider2.py
from bs4 import BeautifulSoup
from multiprocessing import Pool
import requests
import time
import pymongo

client = pymongo.MongoClient('localhost', 27017)
ganji = client['ganji']
t_urllist = ganji['t_urllist']
t_detail = ganji['t_detail']

#
# 解析基于“轉(zhuǎn)轉(zhuǎn)”平臺(tái)的頁(yè)面
#
def parse_zz_detail(url):
    web_data = requests.get(url)
    soup = BeautifulSoup(web_data.text, 'lxml')
    if soup.find('span', 'soldout_btn'):
        print('商品下架啦!' + url)
        pass
        # Nothing !
    else:
        titles = soup.select('body > div.content > div > div.box_left > div.info_lubotu.clearfix > div.box_left_top > h1')
        prices = soup.select('body > div.content > div > div.box_left > div.info_lubotu.clearfix > div.info_massege.left > div.price_li > span > i')
        areas = soup.select('body > div.content > div > div.box_left > div.info_lubotu.clearfix > div.info_massege.left > div.palce_li > span > i')
        categories = soup.select('#nav > div')
        data = {
            'url': url,
            'title': titles[0].get_text().strip(),
            'price': prices[0].get_text().strip(),
            'area': areas[0].get_text().strip(),
            'category': list(categories[0].stripped_strings)[-1]
        }
        # print(data)
        t_detail.insert_one(data)


#
# 解析基于趕集自身平臺(tái)的頁(yè)面
#
def parse_nm_detail(url):
    web_data = requests.get(url)
    if web_data.status_code == 404:
        print('商品下架啦!' + url)
        pass
        # Nothing !
    else:
        soup = BeautifulSoup(web_data.text, 'lxml')
        titles = soup.select(
            '#wrapper > div.content.clearfix > div.leftBox > div.col-cont.title-box > h1')
        prices = soup.select(
            '#wrapper > div.content.clearfix > div.leftBox > div > div > ul > li > i.f22.fc-orange.f-type')
        areas = soup.select(
            '#wrapper > div.content.clearfix > div.leftBox > div:nth-of-type(2) > div > ul > li:nth-of-type(3) > a')
        categories = soup.select('#wrapper > div.content.clearfix > div.leftBox > div:nth-of-type(2) > div > ul > li:nth-of-type(1) > span > a')
        data = {
                'url': url,
            'title': titles[0].get_text().strip(),
            'price': prices[0].get_text().strip(),
            'area': list(map(lambda x:x.text, areas)),
            'category': list(categories[0].stripped_strings)[-1]
        }
        # print(data)
        t_detail.insert_one(data)


#
# 通用解析接口
#
def parse_detail(row):
    print(row)
    if row['type'] == 'zz':
        parse_zz_detail(row['url'])
    else:
        parse_nm_detail(row['url'])

    # 標(biāo)記已處理的記錄
    t_urllist.update({'_id': row['_id']}, {'$set':{'flag': True}})


#
# 程序入口 : 從數(shù)據(jù)庫(kù)讀取url,采用多線(xiàn)程進(jìn)行詳情爬取
#
if __name__ == '__main__':
    # parse_detail('http://zhuanzhuan.ganji.com/detail/797106589634494469z.shtml?from=pc&source=ganji&cate=%E5%8C%97%E4%BA%AC%E8%B5%B6%E9%9B%86%7C%E5%8C%97%E4%BA%AC%E4%BA%8C%E6%89%8B%7C%E5%8C%97%E4%BA%AC%E4%BA%8C%E6%89%8B%E6%89%8B%E6%9C%BA&cateurl=bj|wu|shouji', 'zz')
    # parse_detail('http://bj.ganji.com/bangong/2413656831x.htm', 'nm')
    rows = t_urllist.find({'flag': False})
    pool = Pool()
    pool.map(parse_detail, rows)

總結(jié)

  • 趕集網(wǎng)的分頁(yè),第一頁(yè)與第二頁(yè)的規(guī)則不同,第一頁(yè)不能直接拼接“o1/”作為分頁(yè)標(biāo)識(shí)。
  • 趕集的列表及商品頁(yè)面有兩種:基于“轉(zhuǎn)轉(zhuǎn)”平臺(tái)的 和 基于趕集自身平臺(tái)的。在列表識(shí)別以及詳情頁(yè)面爬取時(shí)需要予以區(qū)分處理。
  • 基于轉(zhuǎn)轉(zhuǎn)的列表頁(yè)面中,個(gè)人信息與商家信息的區(qū)分要根據(jù)<tr>標(biāo)簽的css樣式差異。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,781評(píng)論 25 709
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評(píng)論 19 139
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,071評(píng)論 4 61
  • 出行前準(zhǔn)備:護(hù)照、行程安排表、身份證、換泰銖、泳衣、墨鏡、充電寶、訂機(jī)票、訂酒店、打印酒店確認(rèn)單、打印落地簽申請(qǐng)表...
    張小凡是超級(jí)女英雄閱讀 519評(píng)論 5 8
  • 文/源琪琪 賈大方雖然年紀(jì)輕輕,但卻是出了名的紈绔子弟,家里有點(diǎn)小錢(qián),自己便整天不務(wù)正業(yè)花天酒地,還經(jīng)常和各種名媛...
    源源de源琪琪閱讀 683評(píng)論 0 1

友情鏈接更多精彩內(nèi)容