python爬取bilibili数据_python基础教程之selenium+phantomjs爬取bilibili
selenium+phantomjs爬取bilibili
首先我們要下載phantomjs 你可以到 http://phantomjs.org/download.html 這里去下載 下載完之后解壓到你想要放的位置 你需要配置一下環(huán)境變量哦
如下圖:
首先,我們?cè)趺醋尀g覽器模擬操作,也就是我們自己先分析好整個(gè)操作過程,哪個(gè)地方有什么問題,把這些問題都提前測(cè)試好,沒問題了再進(jìn)行寫代碼。
打開bilibili網(wǎng)站 https://www.bilibili.com/ 發(fā)現(xiàn)下圖登陸彈窗
那么這里我們就得先把這個(gè)彈窗去除,怎么去呢?你刷新一下或者點(diǎn)一下 首頁 就不會(huì)出現(xiàn)了,所以這里我們可以模擬再刷新一次或者點(diǎn)擊首頁。
接下來搜索關(guān)鍵詞 蔡徐坤 打球 這時(shí)就涉及到搜索輸入框和搜索按鈕
點(diǎn)擊搜索后我們看到了下列內(nèi)容,其中圈起來的就是要爬的信息啦 這時(shí)就涉及到頁面源碼獲取,數(shù)據(jù)元素定位
那么上面這個(gè)過程走完了的話 我們也可以選擇寫入xls格式,同時(shí)這里還少了一個(gè)事,那就是我現(xiàn)在才爬了一頁,那難道不寫個(gè)自動(dòng)化爬取全部嗎?
那此時(shí)就得解決循環(huán)獲取和寫入xls 更重要的事怎么去操作頁數(shù)和下一頁按鈕
大致的思路就是這樣子了!!!
先導(dǎo)入這些模塊
from selenium import webdriver
from selenium.common.exceptions import TimeoutException #一條命令在足夠的時(shí)間內(nèi)沒有完成則會(huì)拋出異常
from selenium.webdriver.common.by import By #支持的定位器分類
from selenium.webdriver.support.ui import WebDriverWait #等待頁面加載完成,找到某個(gè)條件發(fā)生后再繼續(xù)執(zhí)行后續(xù)代碼,如果超過設(shè)置時(shí)間檢測(cè)不到則拋出異常
from selenium.webdriver.support import expected_conditions as EC #判斷元素是否加載
from bs4 import BeautifulSoup
import xlwt
定義一個(gè)瀏覽器對(duì)象并設(shè)置其他功能
browser = webdriver.Chrome() #初始化瀏覽器對(duì)象
WAIT = WebDriverWait(browser,10) #顯式等待,等待的時(shí)間是固定的,這里為10秒 元素在指定時(shí)間內(nèi)不可見就引發(fā)異常TimeoutException
browser.set_window_size(1400,900) #設(shè)置瀏覽器窗口大小
創(chuàng)建excel文件,再創(chuàng)建一張工作表,名為 蔡徐坤籃球,并且設(shè)置支持覆蓋原數(shù)據(jù)!
book=xlwt.Workbook(encoding='utf-8',style_compression=0) #創(chuàng)建excel文件,設(shè)置utf-8編碼,這樣就可以在excel中輸出中文了
sheet=book.add_sheet('蔡徐坤籃球',cell_overwrite_ok=True) #添加一張工作表 cell_overwrite_ok=True 時(shí)可以覆蓋原單元格中數(shù)據(jù)。
sheet.write(0,0,'名稱')
sheet.write(0,1,'地址')
sheet.write(0,2,'描述')
sheet.write(0,3,'觀看次數(shù)')
sheet.write(0,4,'彈幕數(shù)')
sheet.write(0,5,'發(fā)布時(shí)間')
打開網(wǎng)站
browser.get('https://www.bilibili.com/')
尋找 “首頁” 元素
index = WAIT.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#primary_menu > ul > li.home > a')))
# 配合WebDriverWait類的until()方法進(jìn)行靈活判斷 進(jìn)行下一步操作
# 通過EC進(jìn)行判斷某個(gè)元素中是否可見并且是enable的 這樣的話叫clickable(可點(diǎn)擊)
# 使用CSS選擇器選中頁面中的 首頁 進(jìn)行點(diǎn)擊 目的為了第一次有個(gè)登錄彈窗 刷新就沒有 那就點(diǎn)擊下首頁來實(shí)現(xiàn)刷新
index.click() #點(diǎn)擊!
先判斷是否加載 輸入框 再判斷搜索按鈕是否能點(diǎn)擊 達(dá)到條件后輸入內(nèi)容進(jìn)行搜索
input = WAIT.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#banner_link > div > div > form > input'))) #判斷某個(gè)元素是否被加到DOM樹里,并不代表該元素一定可見(元素可以是隱藏的)
submit = WAIT.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="banner_link"]/div/div/form/button'))) #判斷搜索按鈕是否能點(diǎn)擊,這里使用Xpath來尋找元素
input.send_keys('蔡徐坤 籃球') #用send_keys()方法進(jìn)行搜索輸入框中輸入內(nèi)容
submit.click() #點(diǎn)擊搜索!
這時(shí)搜索完 是彈出新的窗口 這時(shí)就得獲取窗口句柄 實(shí)現(xiàn)標(biāo)簽頁跳轉(zhuǎn)
all_h = browser.window_handles #獲取所有窗口句柄
browser.switch_to.window(all_h[1]) #switch_to.window 標(biāo)簽頁跳轉(zhuǎn)
接下來就是獲取頁面源碼了(此處非全部源碼)
WAIT.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#server-search-app > div.contain > div.body-contain > div > div.result-wrap.clearfix'))) #堅(jiān)持是否加載完所有搜索結(jié)果
html = browser.page_source #page_source方法可以獲取到頁面源碼
然后搜索元素并提取內(nèi)容進(jìn)行保存
#遍歷所有搜索信息 并保存
list = soup.find(class_='all-contain').find_all(class_='info')
for item in list:
item_title = item.find('a').get('title')
item_link = item.find('a').get('href')
item_dec = item.find(class_='des hide').text
item_view = item.find(class_='so-icon watch-num').text
item_biubiu = item.find(class_='so-icon hide').text
item_date = item.find(class_='so-icon time').text
print('爬取:' + item_title)
再最后就是循環(huán)獲取每一頁提取數(shù)據(jù)最后寫入xls文件!!!
下面就直接貼出代碼了
from selenium import webdriver
from selenium.common.exceptions import TimeoutException #一條命令在足夠的時(shí)間內(nèi)沒有完成則會(huì)拋出異常
from selenium.webdriver.common.by import By #支持的定位器分類
from selenium.webdriver.support.ui import WebDriverWait #等待頁面加載完成,找到某個(gè)條件發(fā)生后再繼續(xù)執(zhí)行后續(xù)代碼,如果超過設(shè)置時(shí)間檢測(cè)不到則拋出異常
from selenium.webdriver.support import expected_conditions as EC #判斷元素是否加載
from bs4 import BeautifulSoup
import xlwt
browser = webdriver.Chrome() #初始化瀏覽器對(duì)象
WAIT = WebDriverWait(browser,10) #顯式等待,等待的時(shí)間是固定的,這里為10秒 元素在指定時(shí)間內(nèi)不可見就引發(fā)異常TimeoutException
browser.set_window_size(1400,900) #設(shè)置瀏覽器窗口大小
book=xlwt.Workbook(encoding='utf-8',style_compression=0) #創(chuàng)建excel文件,設(shè)置utf-8編碼,這樣就可以在excel中輸出中文了
sheet=book.add_sheet('蔡徐坤籃球',cell_overwrite_ok=True) #添加一張工作表 cell_overwrite_ok=True 時(shí)可以覆蓋原單元格中數(shù)據(jù)。
sheet.write(0,0,'名稱')
sheet.write(0,1,'地址')
sheet.write(0,2,'描述')
sheet.write(0,3,'觀看次數(shù)')
sheet.write(0,4,'彈幕數(shù)')
sheet.write(0,5,'發(fā)布時(shí)間')
n = 1
def seach():
try:
print('開始訪問b站....')
browser.get('https://www.bilibili.com/')
index = WAIT.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#primary_menu > ul > li.home > a')))
# 配合WebDriverWait類的until()方法進(jìn)行靈活判斷 進(jìn)行下一步操作
# 通過EC進(jìn)行判斷某個(gè)元素中是否可見并且是enable的 這樣的話叫clickable(可點(diǎn)擊)
# 使用CSS選擇器選中頁面中的 首頁 進(jìn)行點(diǎn)擊 目的為了第一次有個(gè)登錄彈窗 刷新就沒有 那就點(diǎn)擊下首頁來實(shí)現(xiàn)刷新
index.click() #點(diǎn)擊!
input = WAIT.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#banner_link > div > div > form > input'))) #判斷某個(gè)元素是否被加到DOM樹里,并不代表該元素一定可見(元素可以是隱藏的)
submit = WAIT.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="banner_link"]/div/div/form/button'))) #判斷搜索按鈕是否能點(diǎn)擊,這里使用Xpath來尋找元素
input.send_keys('蔡徐坤 籃球') #用send_keys()方法進(jìn)行搜索輸入框中輸入內(nèi)容
submit.click() #點(diǎn)擊搜索!
print('跳轉(zhuǎn)到新窗口')
all_h = browser.window_handles #獲取所有窗口句柄
browser.switch_to.window(all_h[1]) #switch_to.window 標(biāo)簽頁跳轉(zhuǎn)
get_source()
total = WAIT.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#server-search-app > div.contain > div.body-contain > div > div.page-wrap > div > ul > li.page-item.last > button"))) #等待加載后獲取所有頁數(shù)按鈕
return int(total.text) #返回頁碼數(shù)量
except TimeoutException:
return seach()
def get_source():
WAIT.until(EC.presence_of_element_located((By.CSS_SELECTOR,'#server-search-app > div.contain > div.body-contain > div > div.result-wrap.clearfix'))) #堅(jiān)持是否加載完所有搜索結(jié)果
html = browser.page_source #page_source方法可以獲取到頁面源碼
soup = BeautifulSoup(html,'lxml')
save_to_excel(soup)
def save_to_excel(soup):
#遍歷所有搜索信息 并保存
list = soup.find(class_='all-contain').find_all(class_='info')
for item in list:
item_title = item.find('a').get('title')
item_link = item.find('a').get('href')
item_dec = item.find(class_='des hide').text
item_view = item.find(class_='so-icon watch-num').text
item_biubiu = item.find(class_='so-icon hide').text
item_date = item.find(class_='so-icon time').text
print('爬取:' + item_title)
global n
sheet.write(n, 0, item_title)
sheet.write(n, 1, item_link)
sheet.write(n, 2, item_dec)
sheet.write(n, 3, item_view)
sheet.write(n, 4, item_biubiu)
sheet.write(n, 5, item_date)
n = n + 1
def next_page(page_num):
try:
print('獲取下一頁數(shù)據(jù)')
next_btn = WAIT.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#server-search-app > div.contain > div.body-contain > div > div.page-wrap > div > ul > li.page-item.next > button')))
#等待加載 下一頁 按鈕
next_btn.click() #點(diǎn)擊下一頁!
WAIT.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,'#server-search-app > div.contain > div.body-contain > div > div.page-wrap > div > ul > li.page-item.active > button'),str(page_num)))
#判斷某個(gè)元素中的text是否包含了預(yù)期的字符串
get_source()
except TimeoutException:
browser.refresh() #刷新頁面
return next_page(page_num)
def main():
try:
total = seach()
for i in range(2,int(total+1)):
next_page(i)
finally:
browser.close()
browser.quit()
if __name__ == '__main__':
main()
book.save(u'蔡徐坤籃球.xls') #在字符串前加r,聲明為raw字符串,這樣就不會(huì)處理其中的轉(zhuǎn)義了。否則,可能會(huì)報(bào)錯(cuò)
總結(jié)
以上是生活随笔為你收集整理的python爬取bilibili数据_python基础教程之selenium+phantomjs爬取bilibili的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: win10以及win10企业版安装ubu
- 下一篇: python从菜鸟到高手李宁pdf_尹成