python使用selenium控制浏览器进行爬虫

这里以谷歌浏览器为例,需要安装一下chromedriver,其他浏览器也有相对应的driver,chromedriver下载地址:https://googlechromelabs.github.io/chrome-for-testing/

然后是打开python环境安装一下依赖pip install selenium,验证一下控制浏览器是否成功

python 复制代码
# -*- coding: utf-8 -*-
from selenium import webdriver

driverPath = r'D:\chromedriver-win64\chromedriver.exe'
driver = webdriver.Chrome(executable_path=driverPath)
url = 'http://www.baidu.com'
driver.get(url)

点击运行脚本可以看到以下页面就成功了。

爬虫的话需要使用到以下相关函数:

python 复制代码
driver.find_element_by_class_name("class")      # 通过class属性值定位
driver.find_element_by_id("id")                 # 通过id值定位
driver.find_element_by_name("name")             # 通过属性名称定位
driver.find_element_by_css_selector("selector") # 通过css选择器定位,格式是('标签名[属性名="属性值"]')
driver.find_element_by_link_text("text")        # 通过超链接文本定位
driver.find_element_by_tag_name("tag")          # 通过标签定位
driver.find_element_by_xpath("path")            # 通过xpath路径定位

还有其他的输入操作send_keys和点击操作click()等等这些基本上满足浏览器的大部分操作需求

相关推荐
老胖闲聊2 小时前
Python PyAutoGUI库【GUI 自动化库】深度解析与实战指南
python
GeekABC4 小时前
FastAPI系列06:FastAPI响应(Response)
开发语言·python·fastapi·web
fen_fen4 小时前
Python3:Jupyter Notebook 安装和配置
ide·python·jupyter
试着5 小时前
playwrite和selenium的区别
selenium·测试工具·playwright
float_六七5 小时前
Python语言基础知识详解:分支结构控制语句
python
声声codeGrandMaster5 小时前
django之优化分页功能(利用参数共存及封装来实现)
数据库·后端·python·django
Johny_Zhao5 小时前
OpenStack 全套搭建部署指南(基于 Kolla-Ansible)
linux·python·信息安全·云计算·openstack·shell·yum源·系统运维
27669582925 小时前
海关 瑞数 后缀分析 rs
java·python·rs·瑞数·海关·瑞数后缀·后缀生成
学c真好玩6 小时前
Django创建的应用目录详细解释以及如何操作数据库自动创建表
后端·python·django
沐暖沐6 小时前
Django(快速上手版)
python·django