前言:最近在学习爬虫时,由于要在同一个函数中实现寻找多个网页元素,找了很多资料也没有发现有能判断元素是否存在的,所以我整理了一下找到的部分答案和我自己写的解决方法。
is_displayed()
有些资料说用is_displayed(),但是这个函数只能在元素确定存在的情况下判断该元素是否存在,如果该元素不存在的话,依然会抛出异常。
代码:
from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = Chrome(options=option)
driver.get('http://www.baidu.com')
driver.find_element_by_xpath('//table[@calss="c-table opr-toplist1-table"]').is_displayed()
driver.find_element_by_xpath('//img[@id="s_lg_img"]').is_displayed()
结果:
try/except处理异常
函数在找不到网页元素的时候,会抛出异常,可以通过try/except捕获该异常进行判断。但是这个方法不能用于需要判断多个元素,因为当前面的元素不存在时,就会跳出程序,处理异常,同时后续的程序将不再执行。
代码:
from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions
import selenium.common.exceptions
try:
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = Chrome(options=option)
driver.get('http://www.baidu.com')
driver.find_element_by_xpath('//img[@id="s_lg_img"]')
print("元素1存在")
driver.find_element_by_xpath('//table[@calss="c-table opr-toplist1-table"]')
print("元素2存在")
except selenium.common.exceptions.NoSuchElementException:
print("元素不存在")
结果:
将元素1和元素2的代码位置交换一下。
代码:
from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions
import selenium.common.exceptions
try:
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = Chrome(options=option)
driver.get('http://www.baidu.com')
driver.find_element_by_xpath('//table[@calss="c-table opr-toplist1-table"]')
print("元素2存在")
driver.find_element_by_xpath('//img[@id="s_lg_img"]')
print("元素1存在")
except selenium.common.exceptions.NoSuchElementException:
print("元素不存在")
结果:
可以看到由于元素2不存在抛出异常并处理后,后续的语句没有继续执行。
解决方法
针对这种情况,我写了一个函数来判断网页中的元素是否存在。
代码:
from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions
import selenium.common.exceptions
def is_element_exist(self, element):
try:
self.find_element_by_xpath(element)
return 1
except selenium.common.exceptions.NoSuchElementException:
return 0
def main():
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = Chrome(options=option)
driver.get('http://www.baidu.com')
if is_element_exist(driver, '//table[@calss="c-table opr-toplist1-table"]'):
print("元素2存在")
else:
print("元素2不存在")
if is_element_exist(driver, '//img[@id="s_lg_img"]'):
print("元素1存在")
else:
print("元素1不存在")
if __name__ == '__main__':
main()
结果: