使用selenium判断标签的元素值是否存在
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!
Fighting~