對于Python selenium操作的總結(二)
--小破站每日登錄投幣30經驗實戰練習一、操作步驟
環境:Python 3.8,selenium庫
在上一章,講述了如何對本地的瀏覽器操作,在此不再進行贅述
由于是練習問題,能盡量復雜,就復雜一點,故此操作步驟為下:


這樣保證了本地地址是127.0.0.1:12306,且成功運行了,
在這里命令列輸入的是:
D:\Application\Google\chrome.exe --remote-debugging-port=12306
前面的則是chrome的本地檔案,你們可能是如下地址:
C:\Program Files\Google\Chrome\Application\chrome.exe
確保瀏覽器打開后,運行下面的代碼,則OK了,
切記不要短時間內多次運行--------
如果想直接通過b站首頁進入的話,則可以用window_bili()方法,修改一下視窗引數即可
二、代碼
#匯入庫
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import ActionChains
import time
#b站每日登錄+給任意視頻投兩個幣(一共30經驗)
#說是任意,其實是每重繪的六個視頻中的第一個
class Openbili(object):
def __init__(self,driver):
self.driver = driver
def window_bing(self):
# 打開bing搜索
self.driver.get("https://cn.bing.com/")
# 搜索并進入bilibili
#用顯式等待,直到搜索框內輸入
searwd = self.wait.until(EC.presence_of_element_located((By.ID, 'sb_form_q')))
searwd.send_keys("bilibili")
searwd.send_keys(Keys.ENTER)
def window_bili(self):
bili = self.driver.find_element_by_partial_link_text("嗶哩嗶哩")
actions = ActionChains(self.driver)
actions.click(bili)
actions.perform()
if not driver.get_cookies():
#30經驗--需要cookies,若沒有相應的賬號cookies的話,這里跳轉至登錄
self.win_login()
#等待用戶登錄后再執行操作
while not driver.get_cookies():
time.sleep(1)
#隨機點開一個視頻
self.driver.switch_to.window(driver.window_handles[1])
video = self.driver.find_element_by_css_selector('a[data-idx="1"][target="_blank"]')
video.click()
#投幣點贊
self.driver.switch_to.window(driver.window_handles[2])
time.sleep(3)
coin = self.driver.find_element_by_css_selector('span[]')
coin.click()
ye = self.driver.find_element_by_css_selector('span[]')
ye.click()
def win_login(self):
#登錄操作--通過選項卡操作嗶哩嗶哩,由于瀏覽器自動化輸入會跳出人機操作,故在此推薦掃碼登錄,不再展示對應代碼
self.driver.switch_to.window(driver.window_handles[1])
cllogin = self.driver.find_element_by_css_selector('div[]')
cllogin.click()
def main(self):
#隱式等待
self.driver.implicitly_wait(10)
#顯式等待
self.wait = WebDriverWait(self.driver, 10)
self.window_bing()
self.window_bili()
if __name__ == '__main__':
#操作通過本地地址打開的瀏覽器
options = Options()
options.add_experimental_option("debuggerAddress", "localhost:12306")
driver = webdriver.Chrome(options=options)
#測驗物件
test = Openbili(driver)
test.main()
三、總結
上面對于嗶哩嗶哩的每天30經驗而言,實戰意義不大,僅作為學習參考,而對于瀏覽器自動化,其延申可針對網頁搶購某樣產品,但由于其可對瀏覽器cookies操作性能,導致會有可能出現使cookies泄露問題,瀏覽器自動化操作,還是慎用較好,如果有一定爬蟲基礎的同學,還可以嘗試抓取一下投幣的視頻標題,簡介,up主資訊,在此就不再演示了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/419008.html
標籤:Python
