Python爬蟲實(shí)現(xiàn)模擬點(diǎn)擊動(dòng)態(tài)頁面
動(dòng)態(tài)頁面的模擬點(diǎn)擊:
以斗魚直播為例:http://www.douyu.com/directory/all
爬取每頁的房間名、直播類型、主播名稱、在線人數(shù)等數(shù)據(jù),然后模擬點(diǎn)擊下一頁,繼續(xù)爬取
代碼如下
#!/usr/bin/python3# -*- coding:utf-8 -*-__author__ = ’mayi’ '''動(dòng)態(tài)頁面的模擬點(diǎn)擊: 模擬點(diǎn)擊斗魚直播:http://www.douyu.com/directory/all 爬取每頁房間名、直播類型、主播名稱、在線人數(shù)等數(shù)據(jù),然后模擬點(diǎn)擊下一頁,繼續(xù)爬取''' from selenium import webdriverimport json # 調(diào)用環(huán)境變量指定的PhantomJS瀏覽器創(chuàng)建瀏覽器對(duì)象,executable_path:指定PhantomJS位置driver = webdriver.PhantomJS(executable_path = r'D:Program Filesphantomjsbinphantomjs')from bs4 import BeautifulSoup class DouyuSpider(object): ''' 爬蟲類 ''' def __init__(self): self.url = 'http://www.douyu.com/directory/all/' self.driver = webdriver.PhantomJS() self.file_name = open('douyu.json', 'w', encoding = 'utf-8') def run(self): ''' 爬蟲開始工作 ''' self.driver.get(self.url) # 循環(huán)處理每一頁,直至最后一頁 page = 1 start_flag = True while True: # 等待3秒,防止訪問過于頻繁 self.driver.implicitly_wait(3) print('正在處理第' + page + '頁......') page += 1 # 解析 soup = BeautifulSoup(self.driver.page_source, 'lxml') # 在線直播部分 online_live = soup.find_all(’ul’, {’id’: ’live-list-contentbox’})[0] # 房間列表 live_list = online_live.find_all(’li’) # 處理每一個(gè)房間 for live in live_list:# 房間名、直播類型、主播名稱、在線人數(shù)# 房間名home_name = live.find_all(’h3’, {’class’: ’ellipsis’})[0].get_text().strip()# 直播類型live_type = live.find_all(’span’, {’class’: ’tag ellipsis’})[0].get_text().strip()# 主播名稱anchor_name = live.find_all(’span’, {’class’: ’dy-name ellipsis fl’})[0].get_text().strip()# 在線人數(shù)online_num = live.find_all(’span’, {’class’ :’dy-num fr’})[0].get_text().strip()# print(home_name, live_type, anchor_name, online_num)item = {}item['房間名'] = home_nameitem['直播類型'] = live_typeitem['主播名稱'] = anchor_nameitem['在線人數(shù)'] = online_numif start_flag: start_flag = False content = '[n' + json.dumps(item)else: content = ',n' + json.dumps(item)self.file_name.write(content) # page_source.find()未找到內(nèi)容則返回-1 if self.driver.page_source.find(’shark-pager-disable-next’) != -1:# 已到最后一頁break # 模擬點(diǎn)擊下一頁 self.driver.find_element_by_class_name(’shark-pager-next’).click() # 爬蟲結(jié)束前關(guān)閉文件 self.file_name.write('n]') self.file_name.close()if __name__ == ’__main__’: douyu = DouyuSpider() douyu.run()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python+unittest+requests 接口自動(dòng)化測(cè)試框架搭建教程2. Python的文本常量與字符串模板之string庫3. 利用CSS制作3D動(dòng)畫4. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼5. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題6. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))7. 一款功能強(qiáng)大的markdown編輯器tui.editor使用示例詳解8. .Net加密神器Eazfuscator.NET?2023.2?最新版使用教程9. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法10. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)
