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()等等这些基本上满足浏览器的大部分操作需求

相关推荐
AI蜗牛之家2 小时前
Qwen系列之Qwen3解读:最强开源模型的细节拆解
人工智能·python
whyeekkk2 小时前
python打卡第48天
开发语言·python
Eiceblue4 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550404 小时前
初级程序员入门指南
javascript·python·算法
程序员的世界你不懂5 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP6 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
树叶@6 小时前
Python数据分析7
开发语言·python
老胖闲聊7 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python
码界奇点7 小时前
Python Flask文件处理与异常处理实战指南
开发语言·python·自然语言处理·flask·python3.11
浠寒AI7 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python