做網(wǎng)站是怎樣賺錢深圳全網(wǎng)營(yíng)銷哪里好
python爬蟲之selenium自動(dòng)化操作
需求:操作淘寶去掉彈窗廣告搜索物品后進(jìn)入百度回退又前進(jìn)
selenium模塊的基本使用
問題:selenium模塊和爬蟲之間具有怎樣的關(guān)聯(lián)?
1、便捷的獲取網(wǎng)站中動(dòng)態(tài)加載的數(shù)據(jù)
2、便捷實(shí)現(xiàn)模擬登錄
什么是selenium模塊?
1、基于瀏覽器自動(dòng)化的一個(gè)模塊
selenium使用流程:
1、環(huán)境安裝:pip install selenium
2、下載一個(gè)瀏覽器的驅(qū)動(dòng)程序(edge瀏覽器為例)
(1)下載路徑:edge瀏覽器驅(qū)動(dòng)
(2)驅(qū)動(dòng)程序和瀏覽器的映射關(guān)系:查看瀏覽器版本,上面鏈接找到相對(duì)應(yīng)版本的驅(qū)動(dòng)后下載到爬蟲程序所在文件路徑中。
3、實(shí)例化一個(gè)瀏覽器對(duì)象
4、編寫基于瀏覽器自動(dòng)化的操作代碼
(1)發(fā)起請(qǐng)求:get(url)
(2)標(biāo)簽定位:find系列的方法
(3)標(biāo)簽交互:send_keys(‘xxx’)
(4)執(zhí)行js程序:excute_script(‘jsCode’)
(5)前進(jìn),后退:back(),forward()
(6)關(guān)閉瀏覽器:quit()
實(shí)現(xiàn)代碼如下:
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
# selenium 4版本必須要設(shè)置瀏覽器選項(xiàng),否則會(huì)閃退
option = webdriver.EdgeOptions()
option.add_experimental_option("detach", True)
# 實(shí)例化瀏覽器驅(qū)動(dòng)對(duì)象,并將配置瀏覽器選項(xiàng)
# driver = webdriver.Edge(options=option)
#實(shí)例化一個(gè)瀏覽器對(duì)象(傳入瀏覽器的驅(qū)動(dòng)程序)
bro = webdriver.Edge(options=option)
bro.get('https://www.taobao.com/')# basic-pop-tmpl-closeBtn
#關(guān)閉廣告彈窗
guanggao_btn = bro.find_element(By.CLASS_NAME,'basic-pop-tmpl-closeBtn')
guanggao_btn.click()#標(biāo)簽定位
search_input = bro.find_element(By.ID,'q')
#標(biāo)簽交互
search_input.send_keys('Iphone')#執(zhí)行一組js程序
bro.execute_script('window.scrollTo(0,document.body.scrollHeight)')
sleep(2)
#點(diǎn)擊搜索按鈕
btn = bro.find_element(By.CLASS_NAME,'btn-search')
btn.click()bro.get('https://www.baidu.com')
sleep(2)
#回退
bro.back()
sleep(2)
#前進(jìn)
bro.forward()sleep(5)bro.quit()