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

相关推荐
曲幽3 小时前
FastAPI 身份验证总踩坑?这份 FastAPI Users “避坑指南”请收好
python·fastapi·web·jwt·oauth2·user·authentication
装不满的克莱因瓶3 小时前
掌握 RNN 与 LSTM 模型结构
人工智能·python·rnn·深度学习·神经网络·ai·lstm
何以解忧,唯有..4 小时前
Python包管理工具pip:从入门到精通
开发语言·python·pip
金銀銅鐵4 小时前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf4 小时前
Python 模块与包的导入导出
前端·后端·python
ice8130331815 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib
copyer_xyf5 小时前
Python venv 虚拟环境
前端·后端·python
林爷万福6 小时前
GitHub 开源光谱数据处理项目推荐
python·光纤光谱仪
copyer_xyf6 小时前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python
Full Stack Developme6 小时前
Spring Bean 依赖注入
python·spring·log4j