实例代码
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
def initialize_driver():
options = Options()
driver = webdriver.Chrome(options=options)
return driver
def find_element_by_id(driver, element_id):
try:
element = driver.find_element_by_id(element_id)
print(element)
except NoSuchElementException:
print(f"Element with ID '{element_id}' not found.")
def find_elements_by_id(driver, element_id):
try:
elements = driver.find_elements_by_id(element_id)
print(elements)
except NoSuchElementException:
print(f"Elements with ID '{element_id}' not found.")
def find_element_by_class(driver, class_name):
try:
element = driver.find_element_by_class_name(class_name)
print(element)
except NoSuchElementException:
print(f"Element with class '{class_name}' not found.")
def find_element_by_xpath(driver, xpath):
try:
element = driver.find_element_by_xpath(xpath)
print(element)
except NoSuchElementException:
print(f"Element with XPath '{xpath}' not found.")
def find_element_by_link_text(driver, link_text):
try:
element = driver.find_element_by_link_text(link_text)
print(element)
except NoSuchElementException:
print(f"Element with link text '{link_text}' not found.")
def find_element_by_partial_link_text(driver, partial_link_text):
try:
element = driver.find_element_by_partial_link_text(partial_link_text)
print(element)
except NoSuchElementException:
print(f"Element with partial link text '{partial_link_text}' not found.")
def find_elements_by_tag_name(driver, tag_name):
try:
elements = driver.find_elements_by_tag_name(tag_name)
print(elements)
except NoSuchElementException:
print(f"Elements with tag name '{tag_name}' not found.")
def retrieve_tags():
driver = initialize_driver()
driver.get('https://www.douban.com')
# 使用封装的函数进行元素查找
find_element_by_id(driver, 'anony-nav')
# find_elements_by_id(driver, 'anony-nav')
# find_element_by_class(driver, 'anony-nav')
# find_element_by_xpath(driver, '//*[@id="anony-nav"]/h1/a')
# find_element_by_link_text(driver, '下载豆瓣 App')
# find_element_by_partial_link_text(driver, '豆瓣')
# find_elements_by_tag_name(driver, 'div')
# find_element_by_tag_name(driver, 'h1')
# find_element_by_link_text(driver, '下载豆瓣 App')
# 关闭WebDriver
driver.quit()
if __name__ == "__main__":
retrieve_tags()
解析:如上代码在脚本通过“find_element_by_id”获取元素对象的时候就一直报错,断点查看“driver”对象是存在的,但是“find_element_by_id”不存在,是因为版本问题吗?
有没有大佬帮忙看一下,刚刚学,不是很懂,谢谢。
应该是版本不同导致的API不同,见:
https://blog.csdn.net/weixin_51637785/article/details/125509483