Python之Selenium(自动化浏览器测试)

1.安装selenium

pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple

2.下载对应版本的浏览器驱动

http://npm.taobao.org/mirrors/chromedriver/

在这里插入图片描述

这是我的。

在这里插入图片描述

把解压后的驱动放在自己的python.exe 目录下。

在这里插入图片描述

3.测试code,打开一个网页,并获取网页的标题

from selenium.webdriver import Chrome


if __name__ == '__main__':
    web = Chrome()
    web.get("https://baidu.com")
    print(web.title)

在这里插入图片描述

在这里插入图片描述

4.一个小样例

from selenium.webdriver import Chrome


if __name__ == '__main__':
    web = Chrome()
    url = 'https://ac.nowcoder.com/acm/home'
    web.get(url)
	# 获取要点击的a标签
    el = web.find_element_by_xpath('/html/body/div/div[3]/div[1]/div[1]/div[1]/div/a')
	# 点击
    el.click()                          # "/html/body/div/div[3]/div[1]/div[2]/div[2]/div[2]/div[1]/h4/a"
    # 爬取想要的内容
    lists = web.find_elements_by_xpath("/html/body/div/div[3]/div[1]/div[2]/div[@class='platform-item js-item ']/div["
                                       "2]/div[1]/h4/a")
    print(len(lists))
    for i in lists:
        print(i.text)


在这里插入图片描述

5.自动输入并跳转

from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
import time

if __name__ == '__main__':
    web = Chrome()
    url = 'https://ac.nowcoder.com/acm/home'
    web.get(url)

    el = web.find_element_by_xpath('/html/body/div/div[3]/div[1]/div[1]/div[1]/div/a')

    el.click()
    time.sleep(1)
    input_el = web.find_element_by_xpath('/html/body/div/div[3]/div[1]/div[1]/div[1]/form/input[1]')
    input_el.send_keys('牛客', Keys.ENTER)
    #  do something

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐