from selenium.common.exceptions import NoSuchElementException
# 封裝一個函數,用來判斷屬性值是否存在
def isElementPresent(driver, path):
"""
用來判斷元素標簽是否存在,
"""
try:
element = driver.find_element_by_xpath(path)
# 原文是except NoSuchElementException, e:
except NoSuchElementException as e:
# 發生了NoSuchElementException異常,說明頁面中未找到該元素,返回False
return False
else:
# 沒有發生異常,表示在頁面中找到了該元素,返回True
return True
寫個刷bilibili火鍋的腳本測試一下:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import json
from selenium.webdriver.support.ui import Select
import time
from selenium.common.exceptions import NoSuchElementException
# 封裝一個函數,用來判斷屬性值是否存在
def isElementPresent(driver, path):
"""
用來判斷元素標簽是否存在,
"""
try:
element = driver.find_element_by_xpath(path)
# 原文是except NoSuchElementException, e:
except NoSuchElementException as e:
# 發生了NoSuchElementException異常,說明頁面中未找到該元素,返回False
return False
else:
# 沒有發生異常,表示在頁面中找到了該元素,返回True
return True
driver = webdriver.Chrome()
def bilibili_yeah():
while True:
if isElementPresent(driver, '/html/body/div[9]/div/div/div/div[2]'):
print("有X號")
driver.find_element_by_xpath('/html/body/div[9]/div/div/div/div[2]').click()
print(u"X點了")
elif isElementPresent(driver, '//*[@id="app"]/article/div[3]/div[2]/div[2]/div[1]/div[1]/div[1]/div[5]'):
print("有按鈕")
driver.find_element_by_xpath('//*[@id="app"]/article/div[3]/div[2]/div[2]/div[1]/div[1]/div[1]/div[5]').click()
print("Clicked")
else:
print("等10s")
time.sleep(10)
driver.get("https://www.bilibili.com/blackboard/xianxing2020bnj.html?anchor=game")
#driver.implicitly_wait(130)
for i in range(40):
time.sleep(1)
print(40-i)
while True:
try:
bilibili_yeah()
except:
print("QAQ出問題等5s")
time.sleep(5)
Nice!