Selenium报错:'Options'对象无'find_element'属性,点击元素失败
解决Selenium调用
find_element触发的AttributeError错误 问题场景
爬取Upwork职位页面时,尝试点击元素触发错误,原代码如下:
from selenium import webdriver from selenium.webdriver.chrome.options import Options options: Options = webdriver.ChromeOptions() options.add_experimental_option("detach", True) driver = webdriver.Chrome(options=options) driver.get ("https://www.upwork.com/nx/jobs/search/?from_recent_search=true&q=webscraping&sort=recency") options.find_element("xpath", '//*[@id="job-1645717982262001664"]/div[1]/div/h3/a').click()
错误信息
Traceback (most recent call last): File "/Users/yatharthmahajan/Documents/Python/pythonProject/webscraper.py", line 8, in <module> options.find_element("xpath", '//*[@id="job-1645717982262001664"]/div[1]/div/h3/a').click() AttributeError: 'Options' object has no attribute 'find_element'
错误原因
find_element方法属于WebDriver实例(即driver对象),错误用Options对象调用该方法,导致触发AttributeError。
修正方案
将调用find_element的对象替换为driver即可,修正后的代码如下:
from selenium import webdriver from selenium.webdriver.chrome.options import Options options: Options = webdriver.ChromeOptions() options.add_experimental_option("detach", True) driver = webdriver.Chrome(options=options) driver.get ("https://www.upwork.com/nx/jobs/search/?from_recent_search=true&q=webscraping&sort=recency") # 替换为driver对象调用方法 driver.find_element("xpath", '//*[@id="job-1645717982262001664"]/div[1]/div/h3/a').click()
额外优化提示
实际爬取时建议添加等待逻辑,避免页面未加载完成导致元素找不到:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 最长等待10秒,直到元素可点击 WebDriverWait(driver, 10).until( EC.element_to_be_clickable(("xpath", '//*[@id="job-1645717982262001664"]/div[1]/div/h3/a')) ).click()
内容的提问来源于stack exchange,提问作者YetyTheCoder
相关产品推荐
相关产品推荐

