Selenium executes js script

Use selenium to directly interact with js in the current page

Execute Js scripts using selenium

To use js, you must first know how to use js. Now, let’s take a simple example. Let’s use 12306 as an example. The date selection box on the home page can only be manually selected for the corresponding time, because it is a readonly attribute, which needs to be changed to auto

If you want to choose automatically, you need to modify it through js. In the console, we can easily operate, as shown in the figure:

If you use selenium, the idea is the same, first remove the readonly attribute through js, and then execute js to change its time and date, the code is as follows

# Base 为上一章节的base.py默认继承下来的东西
from base import Base
import pytest
import time


class TestJs(Base):
    def test_js(self):
        url = 'https://www.12306.cn/index/'
        self.driver.get(url)
        date_js = 'document.getElementById("train_date").removeAttribute("readonly")'
        self.driver.execute_script(date_js)
        time.sleep(2)
        date_js2 = 'document.getElementById("train_date").value="2024-06-30"'
        self.driver.execute_script(date_js2)
        # ss = self.driver.find_element_by_xpath('//*[@id="train_date"]').text
        # print(f'更改之后当前的日期为:{ss}')


if __name__ == '__main__':
    pytest.main(["-vs", "test_chromjs.py"])

Finally: If you don’t want to experience the feeling of not being able to find information when learning, no one answering questions, and giving up after persisting for a few days, here I will share with you some learning resources for automated testing, hoping to give you some guidance on the way forward. Come to help, friends can get it for free if they need it 【保证100%免费】

Collection of software testing interview questions

Our advanced study of automated testing must be to find a high-paying job. The following interview questions are the latest interview materials from first-line Internet companies such as Ali, Tencent, and Byte, and some Byte bosses have given authoritative answers. After completing this set of interview materials, I believe everyone can find a satisfactory job.

How to get the video file:

Guess you like

Origin blog.csdn.net/m0_75277660/article/details/130624696