Python3 + BeautifulSoup 爬取Steam热销商品数据
這次用了BeautifulSoup庫(kù)來(lái)爬取Steam的熱銷商品,BeautifulSoup更側(cè)重的是從頁(yè)面的結(jié)構(gòu)解析,
根據(jù)標(biāo)簽元素等來(lái)爬取數(shù)據(jù),這次遇到兩個(gè)問(wèn)題:
1.Steam熱銷商品列表經(jīng)常有重復(fù)的,所以我建了一個(gè)列表,把爬到的數(shù)據(jù)存進(jìn)去,每次爬的時(shí)候都校驗(yàn)跟列表里有沒(méi)有重復(fù),有的話就跳過(guò),防止重復(fù)爬取。
2.我需要同時(shí)遍歷兩個(gè)表,找到了zip()函數(shù)解決方案,下面簡(jiǎn)單介紹一下。
zip()
大家看下面的實(shí)例應(yīng)該就能明白。
xs = ['我是','你是','他是'] ys = ['第一','第二','第三']for x, y in zip(xs,ys):print(x+y)輸出結(jié)果如下:
我是第一 你是第二 他是第三下面是完整爬蟲代碼,使用的庫(kù)請(qǐng)自行安裝不另做教學(xué):
from bs4 import BeautifulSoup import xlwt,os,time,requestspage = 1 #起始頁(yè)數(shù) total_pages = 3 #總頁(yè)數(shù),爬10頁(yè)請(qǐng)?jiān)O(shè)定為11 count = 1 #每抓到一次游戲名稱增加一次,用來(lái)排序 pool=[] #每次抓到的游戲名稱都會(huì)放進(jìn)pool列表里,用來(lái)去重 document = 'Steam_GameTopSellers' #設(shè)定爬取的數(shù)據(jù)存的excel的檔案名稱 wb = xlwt.Workbook() #創(chuàng)建excel ws = wb.add_sheet("TopSellers") #在excel新增一個(gè)sheet頁(yè) ws.write(0,0,'#')#三個(gè)參數(shù),1:第幾行,2:第幾列,3:輸入什么值 ws.write(0,1,'Game Title') #在excel第一行第二列先行寫入'Game Title' ws.write(0,2,'Released Date') #在excel第一行第三列先行寫入'Released Date' root = os.getcwd() #獲取當(dāng)前工作路徑 date = time.strftime('%Y%m%d',time.localtime(time.time())) #獲取當(dāng)前日期 格式為yyyymmddwhile page<total_pages:url = 'https://store.steampowered.com/search/?tags=597&filter=topsellers&page=%s' % str(page) #設(shè)定url,變量控制頁(yè)數(shù)r = requests.session()res = r.get(url).textsoup = BeautifulSoup(res,"html.parser")game_names = soup.find_all('span',attrs={'class':'title'}) # 遍歷所有span標(biāo)簽,且class屬性值為'title' 即當(dāng)前頁(yè)面所有游戲名稱released_dates = soup.find_all('div',attrs={'class':'col search_released responsive_secondrow'}) #當(dāng)前頁(yè)面所有發(fā)行日期for game_name, released_date in zip(game_names,released_dates): #同時(shí)遍歷連個(gè)列表的方法 for x,y in zip(xs,ys):if game_name.string in pool: #如果爬到的數(shù)據(jù)在我的pool列表里存在的話就跳過(guò),反之繼續(xù)爬continueelse:print('%s .GameName:%s Released on:%s' % (count,game_name.string,released_date.string)) #打印給自己看的pool.append(game_name.string) #把爬到的數(shù)據(jù)增加到pool列表里ws.write(count,0,count) #往excel寫入編號(hào)ws.write(count,1,game_name.string) #往excel寫入游戲名稱ws.write(count,2,released_date.string) #往excel寫入發(fā)行日期count += 1 #每遍歷一次 count 變量 +1 ,用來(lái)排序?qū)懭雃xcel里的順序rate = page / (total_pages - 1)print('--------------------------第%s頁(yè)爬取完成--------------------已完成: %.2f%%' % (str(page),(rate * 100)))page += 1wb.save('%s%s.xls' % (document,date)) #保存excel print('--------------------------爬取完成--------------------------') print('所有數(shù)據(jù)已存至:%s\%s%s.xls' % (root,document,date))爬取結(jié)果(一共爬取1242條數(shù)據(jù),51頁(yè)~60頁(yè)都是重復(fù)的):
結(jié)語(yǔ):
這steam真是。。。后十頁(yè)就是重復(fù)的,我一開(kāi)始以為是有什么防爬機(jī)制,
后來(lái)在實(shí)際頁(yè)面檢查確實(shí)有重復(fù)的情況。
總結(jié)
以上是生活随笔為你收集整理的Python3 + BeautifulSoup 爬取Steam热销商品数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【Unity学习笔记】Unity中的欧拉
- 下一篇: 【单片机毕业设计】【mcuclub-jj