1. 程式人生 > >PythonSpider---爬取淘寶店鋪資訊並匯入excel

PythonSpider---爬取淘寶店鋪資訊並匯入excel

挺久沒更新簡書了,之前一直在忙機器視覺的開題報告,現在又要期末複習,射頻通訊,訊號處理看的腦闊疼,所以決定寫個簡單點的爬蟲,放鬆下,換個環境,也順便鞏固下爬蟲。

12115116-468195201d476537.PNG 圖片來自網路

0.執行環境

  • Python3.6.5
  • Pycharm
  • win10

1.爬蟲思維框架

12115116-b4bcd85b44bf9a20.png 框架

1:從上圖中可以看出本次爬蟲所用到的庫,其中xlsxwriter庫是用來製作excel表格儲存資料的,剩餘兩個庫就不用多說了,爬蟲必備庫,你一定接觸過。
官方xlsxwriter解釋
CSDN博主的精簡版
2:分四個步驟完成,詳見上圖框架。
3:爬取的淘寶頁面

12115116-867aeb8a52849b1b.png 本次所要爬取的資訊

2.可能遇到的問題及解決方案

  • Q1,無法獲取網頁原始碼,得到的text總是為空?
    A1,必須在headers中加入cookie和user-agent,缺一不可。
  • Q2,使用beautifulsoup庫好還是直接正則表示式RE好?
    A2,對於本次爬蟲還是正則表示式好,做了就知道了。==!
  • Q3,如何爬取多個頁面的資訊?
    A3,仔細觀察多個頁面的URL有何區別,本次的URL最後,第一頁是0,第二頁是20,第三頁是40,找規律便可取得所有頁面的URL。
  • Q4,我還有其他疑問怎麼辦?
    A4,在評論區提出,博主會第一時間回覆你的哦!

3.完整程式碼

import requests
import re
import xlsxwriter

def getUrl(page):   # page為[0,10]內的整數
    part1 = 'https://shopsearch.taobao.com/search?app=shopsearch&spm=a230r.7195193.0.0.45xMl6&q=%E9%A3%9F%E5%93%81&tracelog=shopsearchnoqcat&s='
    list = []
    for a in range(0, page):
        part2 = '{}'.format(20*a)
        url = part1 + part2
        list.append(url)
    return list
def getHtmlText(url):
    try:
        headers = {
            隱藏,因為每個人都不一樣,可通過F12獲取,具體方法自行百度
            Cookie 和 User-Agent必須要
        }
        res = requests.get(url, headers=headers, timeout=30)
        res.raise_for_status()
        res.encoding = res.apparent_encoding
        # time.sleep(1)
        return res.text
    except:
        return '網路異常'
def getTaobaoData(text):
    NAME = re.findall('"nick":"(.*?)"', text)
    PLACE = re.findall('"provcity":"(.*?)"', text)
    Totalsold = re.findall('"totalsold":(.*?),', text)
    Procnt = re.findall('"procnt":(.*?),', text)
    return NAME, PLACE, Totalsold, Procnt

def main(page):
    num = 0
    List = getUrl(page)
    TaobaoData = xlsxwriter.Workbook('E:\\taobaodata.xlsx')
    StoresData = TaobaoData.add_worksheet()
    title = [u'店鋪', u'地址', u'銷量', u'產品數']
    StoresData.write_row('A1', title)
    StoresData.set_column('A:D', 25)
    for URL in List:
        Text = getHtmlText(URL)
        name, place, totalsold, procnt = getTaobaoData(Text)
        StoresData.write_column(1+20*num, 0, name)
        StoresData.write_column(1+20*num, 1, place)
        StoresData.write_column(1+20*num, 2, totalsold)
        StoresData.write_column(1+20*num, 3, procnt)
        num += 1
        if not name:
            print('第{}頁爬取失敗'.format(num))
        else:
            print('第{}頁爬取成功'.format(num))
    TaobaoData.close()

if __name__ == '__main__':
    a = input('請輸入需要爬取的頁數(建議小於10):')
    main(int(a))

4.實現效果

12115116-d838ae78f18eac2d.png Excel