Python爬蟲(chóng)實(shí)現(xiàn)模擬點(diǎn)擊動(dòng)態(tài)頁(yè)面
動(dòng)態(tài)頁(yè)面的模擬點(diǎn)擊:
以斗魚(yú)直播為例:http://www.douyu.com/directory/all
爬取每頁(yè)的房間名、直播類(lèi)型、主播名稱(chēng)、在線人數(shù)等數(shù)據(jù),然后模擬點(diǎn)擊下一頁(yè),繼續(xù)爬取
代碼如下
#!/usr/bin/python3# -*- coding:utf-8 -*-__author__ = ’mayi’ '''動(dòng)態(tài)頁(yè)面的模擬點(diǎn)擊: 模擬點(diǎn)擊斗魚(yú)直播:http://www.douyu.com/directory/all 爬取每頁(yè)房間名、直播類(lèi)型、主播名稱(chēng)、在線人數(shù)等數(shù)據(jù),然后模擬點(diǎn)擊下一頁(yè),繼續(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): ''' 爬蟲(chóng)類(lèi) ''' 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): ''' 爬蟲(chóng)開(kāi)始工作 ''' self.driver.get(self.url) # 循環(huán)處理每一頁(yè),直至最后一頁(yè) page = 1 start_flag = True while True: # 等待3秒,防止訪問(wèn)過(guò)于頻繁 self.driver.implicitly_wait(3) print('正在處理第' + page + '頁(yè)......') 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:# 房間名、直播類(lèi)型、主播名稱(chēng)、在線人數(shù)# 房間名home_name = live.find_all(’h3’, {’class’: ’ellipsis’})[0].get_text().strip()# 直播類(lèi)型live_type = live.find_all(’span’, {’class’: ’tag ellipsis’})[0].get_text().strip()# 主播名稱(chēng)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['直播類(lèi)型'] = live_typeitem['主播名稱(chēng)'] = 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:# 已到最后一頁(yè)break # 模擬點(diǎn)擊下一頁(yè) self.driver.find_element_by_class_name(’shark-pager-next’).click() # 爬蟲(chóng)結(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. chat.asp聊天程序的編寫(xiě)方法2. JSP之表單提交get和post的區(qū)別詳解及實(shí)例3. jsp cookie+session實(shí)現(xiàn)簡(jiǎn)易自動(dòng)登錄4. PHP循環(huán)與分支知識(shí)點(diǎn)梳理5. 利用FastReport傳遞圖片參數(shù)在報(bào)表上展示簽名信息的實(shí)現(xiàn)方法6. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能7. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法8. ASP中格式化時(shí)間短日期補(bǔ)0變兩位長(zhǎng)日期的方法9. JavaWeb Servlet中url-pattern的使用10. jsp EL表達(dá)式詳解
