爬取某網站寫的python程式碼

czxin788發表於2019-11-29

    程式碼如下:

import requests
from pyquery import PyQuery
import re
import os
import csv
import datetime
"""
    說明:該程式碼是專門為爬取商品而設計的。
    使用方法:
        1、在本地提前安裝好python3的環境;
        2、直接執行本程式碼;
        3、執行本程式碼完後,會在當前目錄生成一個result.csv檔案,該檔案裡面就存了爬取該站點的商品資訊
    注意事項:在本程式碼執行期間,不能開啟result.csv檔案,因為這樣程式就寫不進去資料了;只能等本程式碼
            全部執行結束後,才能開啟esult.csv檔案進行檢視。
    
"""
def get_html_text(url):
    """
    獲取首頁原始碼
    :param url:
    :return:
    """
    r = requests.get(url)
    return r.text
def get_one_level_class(home_url):
    """
    一級標題
        母嬰用品 mall/list.php?catid=4
        生活家居 mall/list.php?catid=5
    """
    html = get_html_text(home_url)
    jpy = PyQuery(html)
    items = jpy('.menu_title a')
    for line in items:
        jpy = PyQuery(line)
        one_level_url = jpy('a').attr('href')
        one_level_title = jpy('a').text()
        yield one_level_url, one_level_title
def get_two_level_class(home_url):
    """
    二級標題
        母嬰用品 營養輔食 mall/search.php?catid=539
        母嬰用品 媽媽專區 mall/search.php?catid=544
        母嬰用品 嬰兒保健 mall/search.php?catid=887
    """
    for one_level_url, one_level_title in get_one_level_class(home_url):
        jpy = PyQuery(one_level_url)
        items = jpy('.selector_category li')
        for line in items:
            jpy = PyQuery(line)
            two_level_url = jpy('a').attr('href')
            two_level_title = jpy('a').text()
            yield one_level_title, two_level_title, two_level_url
def get_pages(url):
    """
    獲取頁數
    :return:
    """
    jpy = PyQuery(url)
    pages = jpy('.pagination cite').text()
    print('原pages:', pages)
    try:
        pages = int(re.findall('共.*?條/(.*)頁', pages)[0])
    except Exception as e:
        print(e)
        pages = 1
    print('頁碼:', pages)
    return pages
def get_three_level_class(home_url):
    """
    三級標題
        母嬰用品 營養輔食 DHA mall/search.php?catid=548
        母嬰用品 營養輔食 益生菌/初乳 mall/search.php?catid=549
        母嬰用品 營養輔食 清火/開胃/驅蟲 mall/search.php?catid=550
    """
    for one_level_title, two_level_title, two_level_url in get_two_level_class(home_url):
        jpy = PyQuery(two_level_url)
        items = jpy('.selector_category li')
        for line in items:
            jpy = PyQuery(line)
            three_level_title = jpy('a').text()
            three_level_url = jpy('a').attr('href')
            catid = re.findall('mall/search.php\?catid=(.*)', three_level_url)[0]
            pages = get_pages(three_level_url)
            # for index in range(1, 3):
            for index in range(1, pages + 1):
                three_level_url_by_xiaoliang = 'mall/search.php?kw=&list=0&catid={}&order=10&minprice=&maxprice=&page={}'.format(
                catid, index)
                yield one_level_title, two_level_title, three_level_title, three_level_url_by_xiaoliang
def shop_title_and_url(home_url):
    """
    商品標題和url
        母嬰用品 營養輔食 DHA 澳洲直郵 澳大利亞RIFOLD 兒童DHA90粒(一月以上適用) mall/show.php?itemid=28089
        母嬰用品 營養輔食 益生菌/初乳 澳大利亞 Maxigenes美可卓 全脂高鈣奶粉(藍胖子)1kg 兩罐裝 mall/show.php?itemid=23486
    """
    for one_level_title, two_level_title, three_level_title, three_level_url_by_xiaoliang in get_three_level_class(home_url):
        jpy = PyQuery(three_level_url_by_xiaoliang)
        items = jpy('.list_img a')
        for line in items:
            jpy = PyQuery(line)
            shop_url = jpy('a').attr('href')
            shop_title = jpy('a img').attr('alt')
            yield one_level_title, two_level_title, three_level_title, shop_title, shop_url
def get_shop_info(home_url, count):
    for one_level_title, two_level_title, three_level_title, shop_title, shop_url in shop_title_and_url(home_url):
        print('--排錯:' + one_level_title, two_level_title, three_level_title, shop_title, shop_url)
        jpy = PyQuery(shop_url)
        price = jpy('.price').text()
        # 條形碼
        bar_code = jpy('.bar_code dl dd p').text()
        goods_detail = jpy('#content')
        try:
            guige = re.findall('規格:(.*)', goods_detail.text())[0]
        except:
            guige = '沒有規格'
        try:
            chandi = re.findall('產地:(.*)', goods_detail.text())[0]
        except:
            chandi = '沒有產地'
        print(count, one_level_title, two_level_title, three_level_title, shop_title,  bar_code, chandi, guige,  price, shop_url)
        row = ([one_level_title, two_level_title, three_level_title, shop_title,  bar_code, chandi, guige,  price, shop_url])
        ppath = os.path.dirname(__file__)
        csv_file = ppath + '/result.csv'
        # newline是為了解決csv檔案裡面有多餘的空行,encoding是為了解決寫不進csv資料包字符集的報錯
        with open(csv_file, 'a', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow(row)
        count += 1
def main():
    # 記錄一下開始時間
    start_time = datetime.datetime.now()
    home_url = ''
    # 當前程式碼路徑
    ppath = os.path.dirname(__file__)
    csv_file = ppath + '/result.csv'
    headers = (['一級分類', '二級分類', '三級分類', '商品名稱', '條碼', '產地', '規格', '價格', '商品連結'])
    # newline是為了解決csv檔案裡面有多餘的空行,encoding是為了解決寫不進csv資料包字符集的報錯
    with open(csv_file, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(headers)
    count = 1
    get_shop_info(home_url, 1)
    # 記錄一下結束時間
    end_time = datetime.datetime.now()
    # 記錄程式執行用時
    timediff = end_time - start_time
    print('總共用時{}秒\n'.format(str(timediff.seconds)))
    print('全部商品已經按需求完成!!!')
if __name__ == '__main__':
    main()


    執行後,會在當前目錄下生成個result.csv檔案,內容如下:


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28916011/viewspace-2666192/,如需轉載,請註明出處,否則將追究法律責任。

相關文章