PyCharm中Selenium使用问题:环境已更新但无法调用方法
问题修复方案
你的两个问题都源于Selenium 4.x版本的API变更,以下是具体修复说明和修正代码:
错误原因解析
版本1报错
WebDriver object has no attribute 'find_element_by_id':
Selenium 4.3.0+已彻底移除find_element_by_id、find_element_by_xpath等旧版定位方法,必须改用find_element()配合By类的新语法。同时你的代码重复初始化了driver对象,属于冗余操作。版本2报错
TypeError: WebDriver.__init__() got an unexpected keyword argument 'executable_path':
Selenium 4.x不再支持在webdriver.Chrome()中直接传入executable_path参数,需通过ChromeService类指定ChromeDriver路径。
修正后的完整代码
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 替换为你的ChromeDriver实际路径 chrome_driver_path = "/Users/myusername/Documents/pythonProject1/chromedriver" # 配置Service和浏览器选项 service = Service(chrome_driver_path) options = webdriver.ChromeOptions() # 初始化浏览器驱动 driver = webdriver.Chrome(service=service, options=options) try: # 打开目标商品页面 target_url = "https://www.amazon.com/Coleshome-Computer-Writing-Workstation-Vintage/dp/B0B6V83D3Q/?_encoding=UTF8&pd_rd_w=dhBqd&content-id=amzn1.sym.5f7e0a27-49c0-47d3-80b2-fd9271d863ca%3Aamzn1.symc.e5c80209-769f-4ade-a325-2eaec14b8e0e&pf_rd_p=5f7e0a27-49c0-47d3-80b2-fd9271d863ca&pf_rd_r=TAX9FJM5MT6DWYCYYMRD&pd_rd_wg=b356N&pd_rd_r=b79c530e-5b03-411d-8957-0ec821732764&ref_=pd_gw_ci_mcx_mr_hp_atf_m" driver.get(target_url) # 显式等待价格元素加载(避免页面未加载完成导致定位失败) price_element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "priceblock_ourprice")) ) # 打印商品价格 print("商品价格:", price_element.text) finally: # 确保浏览器实例关闭 driver.quit()
额外注意事项
- 亚马逊存在反爬机制,若遇到验证码或元素定位失败,可添加
options.add_argument("--disable-blink-features=AutomationControlled")规避自动化检测 - 亚马逊商品价格元素的ID可能随商品类型变化(如促销商品会用
priceblock_dealprice),可通过浏览器开发者工具确认当前页面的实际元素ID - 始终保持ChromeDriver版本与Chrome浏览器版本完全匹配,否则会出现兼容性问题
内容的提问来源于stack exchange,提问作者Jimmy Johns
相关产品推荐
相关产品推荐

