想用actionChains滚动页面,但是执行这行self.driver = webdriver.Chrome(options=option)有报错

问题麻烦老师帮忙看看呢,这个和selenium版本有关系吗?

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By

class TestAction:
    def setup(self):
        option = webdriver.ChromeOptions()
        option.add_experimental_option('w3c',False)
        self.driver = webdriver.Chrome(options=option)
        self.driver.get("https://www.baidu.com/s?wd=%E9%93%B8%E7%89%A2%E4%B8%AD%E5%8D%8E%E6%B0%91%E6%97%8F%E5%85%B1%E5%90%8C%E4%BD%93%E6%84%8F%E8%AF%86&sa=fyb_n_homepage&rsv_dl=fyb_n_homepage&from=super&cl=3&tn=baidutop10&fr=top1000&rsv_idx=2&hisfilter=1")
        self.driver.implicitly_wait(5)
    def test_roll(self):

        # 创建一个ActionChains对象
        actions = ActionChains(self.driver)
        # 将鼠标移动到需要滑动的位置(例如页面顶部)
        actions.move_to_element_with_offset(self.driver.find_element(By.XPATH, '//*[@id="su"]'), xoffset=0, yoffset=0)
        # 按住鼠标左键
        actions.click_and_hold()
        # 设置滑动距离和方向(例如向下滑动1000像素)
        actions.move_by_offset(0, -1000)
        # 释放鼠标左键
        actions.release()
        # 执行滑动操作
        actions.perform()

报错信息

/Users/apple/Documents/PycharmProject2024/pythonProjectWeb/venv/bin/python “/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pycharm/_jb_pytest_runner.py” --target test_touchaction.py::TestTouchAction.test_touchaction_scrollbottom
Testing started at 17:10 …
Launching pytest with arguments test_touchaction.py::TestTouchAction::test_touchaction_scrollbottom --no-header --no-summary -q in /Users/apple/Documents/PycharmProject2024/pythonProjectWeb

============================= test session starts ==============================
collecting … collected 1 item

test_touchaction.py::TestTouchAction::test_touchaction_scrollbottom ERROR [100%]
test setup failed
self = <test_touchaction.TestTouchAction object at 0x7fe3a9e8fa30>

def setup(self):
    option = webdriver.ChromeOptions()
    option.add_experimental_option('w3c', False)
  self.driver = webdriver.Chrome(options=option)

test_touchaction.py:12:


venv/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py:45: in init
super().init(
venv/lib/python3.8/site-packages/selenium/webdriver/chromium/webdriver.py:56: in init
super().init(
venv/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py:205: in init
self.start_session(capabilities)
venv/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py:289: in start_session
response = self.execute(Command.NEW_SESSION, caps)[“value”]
venv/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py:344: in execute
self.error_handler.check_response(response)


self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x7fe3a9e8fee0>
response = {‘sessionId’: ‘4523ea02f7ce4b0806280bd243aae6e6’, ‘status’: 33, ‘value’: {‘message’: ‘session not created: Missing or …0.4044.69 (6813546031a4bc83f717a2ef7cd4ac6ec1199132-refs/branch-heads/4044@{#776}),platform=Mac OS X 10.16.0 x86_64)’}}

def check_response(self, response: Dict[str, Any]) -> None:
    """Checks that a JSON response from the WebDriver does not have an
    error.

    :Args:
     - response - The JSON response from the WebDriver server as a dictionary
       object.

    :Raises: If the response contains an error message.
    """
    status = response.get("status", None)
    if not status or status == ErrorCode.SUCCESS:
        return
    value = None
    message = response.get("message", "")
    screen: str = response.get("screen", "")
    stacktrace = None
    if isinstance(status, int):
        value_json = response.get("value", None)
        if value_json and isinstance(value_json, str):
            import json

            try:
                value = json.loads(value_json)
                if len(value) == 1:
                    value = value["value"]
                status = value.get("error", None)
                if not status:
                    status = value.get("status", ErrorCode.UNKNOWN_ERROR)
                    message = value.get("value") or value.get("message")
                    if not isinstance(message, str):
                        value = message
                        message = message.get("message")
                else:
                    message = value.get("message", None)
            except ValueError:
                pass

    exception_class: Type[WebDriverException]
    e = ErrorCode()
    error_codes = [item for item in dir(e) if not item.startswith("__")]
    for error_code in error_codes:
        error_info = getattr(ErrorCode, error_code)
        if isinstance(error_info, list) and status in error_info:
            exception_class = getattr(ExceptionMapping, error_code, WebDriverException)
            break
    else:
        exception_class = WebDriverException

    if not value:
        value = response["value"]
    if isinstance(value, str):
        raise exception_class(value)
    if message == "" and "message" in value:
        message = value["message"]

    screen = None  # type: ignore[assignment]
    if "screen" in value:
        screen = value["screen"]

    stacktrace = None
    st_value = value.get("stackTrace") or value.get("stacktrace")
    if st_value:
        if isinstance(st_value, str):
            stacktrace = st_value.split("\n")
        else:
            stacktrace = []
            try:
                for frame in st_value:
                    line = frame.get("lineNumber", "")
                    file = frame.get("fileName", "<anonymous>")
                    if line:
                        file = f"{file}:{line}"
                    meth = frame.get("methodName", "<anonymous>")
                    if "className" in frame:
                        meth = f"{frame['className']}.{meth}"
                    msg = "    at %s (%s)"
                    msg = msg % (meth, file)
                    stacktrace.append(msg)
            except TypeError:
                pass
    if exception_class == UnexpectedAlertPresentException:
        alert_text = None
        if "data" in value:
            alert_text = value["data"].get("text")
        elif "alert" in value:
            alert_text = value["alert"].get("text")
        raise exception_class(message, screen, stacktrace, alert_text)  # type: ignore[call-arg]  # mypy is not smart enough here
  raise exception_class(message, screen, stacktrace)

E selenium.common.exceptions.SessionNotCreatedException: Message: session not created: Missing or invalid capabilities
E (Driver info: chromedriver=81.0.4044.69 (6813546031a4bc83f717a2ef7cd4ac6ec1199132-refs/branch-heads/4044@{#776}),platform=Mac OS X 10.16.0 x86_64)

venv/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py:229: SessionNotCreatedException

=============================== 1 error in 0.96s ===============================

Process finished with exit code 1

环境

selenium版本4.14.0
浏览器版本

chromedriver版本:

option.add_experimental_option('w3c',False)
把这个注释掉试试

去掉就飘红了

我的意思是把这一整行注释掉

注释了还是不行