Python BeautifulSoup 實戰演練

前幾天獲取到一個比較有意思的需求,在天貓超市,輸入關鍵字,把查詢返回第一頁的商品圖片下載下來;基於這麼個需求,開始去實施

思路:



我這邊採取從excel中讀取商品名稱

excel讀取方法:

#coding=utf-8
import xlrd
from xlutils.copy import copy

'''
從excel中讀取要查找的商品名稱,第一列默認爲0
'''
def Read_Good_Name(xpath,col_index=None):
    col_index = int(col_index)
    #打開xls格式文件,並保存之前數據的格式
    rb = xlrd.open_workbook(xpath,formatting_info=True)
    #獲取當前sheet頁
    r_sheet = rb.sheet_by_index(0)
    #獲取總行數
    table_row_nums = r_sheet.nrows
    list = []
    #進行格式轉換
    for i in range(1,table_row_nums):
        #按列讀取行值
        cvalue = r_sheet.cell(i,col_index).value
        if type(cvalue).__name__ == 'unicode':
            cvalue = cvalue.encode('utf-8')
        elif type(cvalue).__name__ == 'float':
            cvalue = str(int(cvalue))
        #保存到list中
        list.append(cvalue)
    return list

查找商品並保存圖片--解決了中文字符亂碼問題。。。


#coding:utf-8
import requests
import os
from bs4 import BeautifulSoup
import uuid
import urllib
import excel_md
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
'''
按商品名稱創建文件夾
'''
def mkdir(key):
    key = str(key)
    path = os.getcwd()   				     # 獲取此腳本所在目錄
    new_path = os.path.join(path,'picture\\%s'%(key).encode("gbk"))
    if not os.path.isdir(new_path):
        os.mkdir(new_path)
    return new_path
'''
查找圖片url,並保存到txt文件
'''

def search(key):
    #搜索地址
    search_url = 'https://list.tmall.com//search_product.htm?q=%s&user_id=725677994&type=p&cat=50514008&spm=1.1.a2227oh.d100&from=chaoshi..pc_1_searchbutton'%(key)

    #建立request Session
    session = requests.Session()
    req = session.get(search_url)
    content = req.text
    #使用BeautifulSoup解析響應報文
    soup = BeautifulSoup(content, "html.parser")
    #查找tag 爲div,且屬性class名稱爲product-img的數據
    good_pic = soup.find_all('div',attrs={'class':'product-img'})

    #新建空list
    links = []
    for i in good_pic:
        #查找tag 爲img的信息
        jokes = i.find('img')
        #返回img 中data-ks-lazyload 值1
        link = str(jokes.get('data-ks-lazyload'))
        #截取倒數第12個字符前的str
        x = "http:"+link[:-12]
        #添加到列表中
        links.append(x)
        #保存地址到txt
    f1 = open('list_%s_url.txt'%(key).decode("utf-8"),'w')
    for i in links:
        #寫入url
        f1.write(i)
        #換行
        f1.write("\n")
    f1.close()


#生成一個文件名字符串
def generateFileName():
    return str(uuid.uuid1())

#根據文件名創建文件
def createFileWithFileName(localPathParam,fileName):
    totalPath=localPathParam+'\\'+fileName
    if not os.path.exists(totalPath):
        file=open(totalPath,'a+')
        file.close()
        return totalPath

#根據圖片的地址,下載圖片並保存在本地
def getAndSaveImg(imgUrl,path):
        imgUrl = str(imgUrl)
        if( len(imgUrl)!= 0 ):
            fileName=generateFileName()+'.jpg'
            urllib.urlretrieve(imgUrl,createFileWithFileName(path,fileName))


if __name__ == "__main__":  #程序運行入口
        #從excel中讀取商品名稱
        Good_list = excel_md.Read_Good_Name("test.xls",0,0)
        #遍歷商品名稱
        for key in Good_list:
            #查找商品
            search(key)
            #圖片url保存到txt
            file_object = open("list_%s_url.txt"%(key).decode("utf-8"),'r')
            links = []
            for line in file_object:
                #給遍歷出來的圖片url加上http頭

                #保存圖片
                getAndSaveImg(line,mkdir(key))



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章