Python Selenium无法定位class为price的div元素,报NoSuchElementException
问题分析与修正方案
核心错误点
- 定位属性混淆:你要找的元素是
class="price",但代码里误用了By.ID, 'price'——ID和CLASS是完全不同的HTML属性,这是导致找不到元素的直接原因。 - 等待条件无效:代码里用了
wait.until(page_has_loaded),但page_has_loaded并未定义,WebDriverWait无法正确判断页面加载状态,导致元素还未渲染就触发查找操作。 - User-Agent未生效:你定义了
headers但没有通过Selenium的Options配置到浏览器中,可能导致页面渲染异常。
修正后的代码
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 配置浏览器选项 options = Options() options.page_load_strategy = 'eager' # 设置User-Agent user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36' options.add_argument(f'user-agent={user_agent}') # ChromeDriver路径用原始字符串避免转义问题 ser = Service(executable_path=r'C:\webdrivers\chromedriver.exe') def get_first_price(): with webdriver.Chrome(service=ser, options=options) as driver: driver.get('https://cs.deals/market/csgo/Container/?name=phoeni&sort=price') wait = WebDriverWait(driver, 10) # 等待第一个price元素可见 price_element = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'price'))) # 提取纯价格文本(分离折扣部分) full_text = price_element.text price = full_text.split('\n')[0].strip() print(f"第一个最低价格:{price}") if __name__ == "__main__": get_first_price()
关键说明
- 元素定位:用
By.CLASS_NAME, 'price'匹配目标元素,find_element(含等待条件返回的元素)默认返回页面中第一个符合条件的元素,正好对应你要的最低价格。 - 等待逻辑:用
EC.visibility_of_element_located确保元素完全渲染可见后再操作,避免因页面未加载完成导致的找不到元素异常。 - 价格提取:元素文本包含价格和折扣两行,用
split('\n')分割后取第一行即可拿到纯价格内容。
内容的提问来源于stack exchange,提问作者Do0dl3r
相关产品推荐
相关产品推荐

