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

相关推荐
IVEN_3 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang4 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮4 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling4 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮7 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽8 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers