Python Selenium调用PhantomJS报错:TypeError: 'module' object is not callable
搞定Selenium里PhantomJS的TypeError: 'module' object is not callable错误
Hey, I’ve run into this exact issue before! Let’s figure out what’s going wrong and fix it step by step.
问题根源
你代码里的webdriver.phantomjs是一个模块对象,不是可直接调用的方法——这就是为什么会抛出TypeError: 'module' object is not callable的核心原因。
修正后的代码
在Selenium中,调用PhantomJS的正确方式是使用首字母大写的webdriver.PhantomJS(),同时注意路径里的反斜杠要转义(用双反斜杠\\或者正斜杠/):
from selenium import webdriver # 修正调用方法名,同时处理路径转义问题 driver = webdriver.PhantomJS(executable_path='D:\\python\\scrapy\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe') url='https://google.com' driver.get(url) # 记得操作完成后关闭驱动,避免资源占用 driver.quit()
额外建议
顺便提一句:PhantomJS已经停止维护了,后续可能会遇到更多兼容性问题。现在Selenium官方更推荐使用Chrome Headless或者Firefox Headless模式,这里给你一个Chrome Headless的示例参考:
from selenium import webdriver from selenium.webdriver.chrome.options import Options # 配置无头模式 chrome_options = Options() chrome_options.add_argument("--headless=new") # 初始化驱动 driver = webdriver.Chrome(options=chrome_options) driver.get("https://google.com") # 这里可以添加你的页面操作逻辑 # 最后关闭驱动 driver.quit()
内容的提问来源于stack exchange,提问作者Nithin
相关产品推荐
相关产品推荐

