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

相关推荐
ZTLJQ4 小时前
序列化的艺术:Python JSON处理完全解析
开发语言·python·json
H5css�海秀4 小时前
今天是自学大模型的第一天(sanjose)
后端·python·node.js·php
阿贵---5 小时前
使用XGBoost赢得Kaggle比赛
jvm·数据库·python
无敌昊哥战神5 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
李昊哲小课6 小时前
第1章-PySide6 基础认知与环境配置
python·pyqt·pyside
2401_894241927 小时前
用Pygame开发你的第一个小游戏
jvm·数据库·python
Zzzz_my8 小时前
正则表达式(RE)
pytorch·python·正则表达式
天天鸭8 小时前
前端仔写了个 AI Agent,才发现大模型只干了 10% 的活
前端·python·ai编程
setmoon2149 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
2401_833197739 小时前
为你的Python脚本添加图形界面(GUI)
jvm·数据库·python