用Selenium开启自动化网页交互与数据抓取之旅

用Selenium开启自动化网页交互与数据抓取之旅

在当今数字化时代,数据的价值不言而喻,而网页作为海量数据的重要载体,如何高效获取其中的关键信息成为众多开发者和数据爱好者关注的焦点。Selenium这一强大工具,为我们打开了自动化操作网页和精准抓取数据的大门。今天,就来和大家深入聊聊Selenium的使用。

一、Selenium是什么

Selenium本质上是一款用于Web应用程序测试的工具,但它的用途远不止于此。简单来说,它可以驱动各种浏览器,像Chrome、Firefox、Edge等,按照我们编写的脚本代码去执行一系列操作,比如点击按钮、输入文本、打开网页以及验证页面元素等,模拟真实用户在浏览器上的行为。这意味着我们可以借助它实现网页操作的自动化,无论是繁琐的重复性任务,还是复杂的数据采集工作,都能轻松应对。

二、Selenium的工作原理

浏览器能够被Selenium驱动,关键在于webdriver驱动程序。不同的浏览器需要对应不同版本的webdriver,例如Chrome浏览器就有专门为其开发的chromedriver。webdriver就像是浏览器的"遥控器",通过与浏览器内核进行交互,控制浏览器执行我们设定的命令。这就要求在使用Selenium时,务必确保下载的webdriver版本与所使用的浏览器版本相匹配,否则可能会出现各种兼容性问题。

三、Selenium的使用方法

(一)使用前的准备工作

  1. 安装Selenium库 :安装Selenium非常简单,使用pip命令即可。在命令行中输入pip install selenium -i https://pypi.mirrors.ustc.edu.cn/simple/,就能快速完成安装。如果使用的是PyCharm等集成开发环境,也可以在其界面中轻松完成安装操作。
  2. 下载浏览器内核驱动 :以Chrome浏览器为例,其内核驱动地址为https://chromedriver.storage.googleapis.com/index.html 。下载后,根据不同的操作系统进行相应的配置。在Windows系统中,解压下载的文件,并将其放置在Python安装目录的Scripts文件夹下;Linux和Mac系统类似,但要注意系统中可能存在多个Python版本,需确保配置的是当前运行的Python版本的环境变量。

(二)基本操作示例

  1. 打开网页并进行搜索:下面这段代码展示了如何使用Selenium打开苏宁易购网站,并搜索"手机"。
python 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys

__browser_url = r"C:\Program Files\Google\Chrome\Application\chrome.exe" 
chrome_options = Options()
chrome_options.binary_location = __browser_url    
driver = webdriver.Chrome(options=chrome_options)  

driver.get('https://www.suning.com/') 
driver.find_element_by_id("searchKeywords").send_keys("手机" + Keys.RETURN)

在这段代码中,首先创建了一个Options对象,用于配置浏览器的相关参数,然后指定Chrome浏览器的安装路径,初始化Chrome驱动。接着使用get方法打开苏宁易购网站,再通过find_element_by_id找到搜索框元素,并使用send_keys方法输入"手机"并回车,完成搜索操作。

  1. 获取网页元素信息:在网页数据抓取中,获取元素信息是关键步骤。比如,我们可以获取网页上某个元素的文本内容、属性值、位置、标签名以及大小等信息。下面以获取苏宁易购手机商品评论为例:
python 复制代码
from selenium import webdriver
from selenium.webdriver.edge.options import Options
import time

__browser_url = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" 
chrome_options = Options()
chrome_options.binary_location = __browser_url    
driver = webdriver.Edge(options=chrome_options)  

from selenium.webdriver.common.by import By
driver.get('https://review.suning.com/cluster_cmmdty_review/cluster-38249278-000000012389328846-0000000000-1-good.htm?originalCmmdtyType=general&safp=d488778a.10004.loverRight.166')

yzpj_file = open('优质评价1.txt','w')
def get_py_content(file):
    pj_elments_content = driver.find_elements(by=By.CLASS_NAME,value= 'body-content')
    for i in range(len(pj_elments_content)):
        file.write(pj_elments_content[i].text+'\n')
get_py_content(yzpj_file)

next_elements = driver.find_elements_by_xpath('//*[@class="next rv-maidian "]')
print(next_elements)
while next_elements !=[]:
    next_element = next_elements[0]
    time.sleep(1)
    next_element.click()
    get_py_content(yzpj_file)
    next_elements = driver.find_elements_by_xpath('//*[@class="next rv-maidian "]')
yzpj_file.close()

这段代码实现了从苏宁易购手机商品评价页面抓取优质评价的功能。首先打开指定的评价页面,然后定义了一个函数get_py_content,通过find_elements方法根据类名查找所有评价内容的元素,并将其文本写入文件。接着,使用find_elements_by_xpath方法查找"下一页"按钮元素,通过循环点击"下一页"按钮,持续获取并保存多页的评价内容。

(三)其他常用操作

  1. 前进、后退与刷新:在浏览网页时,前进、后退和刷新是常见操作,Selenium同样支持这些功能。
python 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

__browser_url = r"D:\Program Files (x86)\360Roaming\360se6\Application\360se.exe" 
chrome_options = Options()
chrome_options.binary_location = __browser_url

driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get('http://www.taobao.com')  
driver.get('http://www.baidu.com')
driver.get('http://www.qq.com')
driver.back()  
time.sleep(5)  
driver.forward() 
time.sleep(5)
driver.refresh()  
driver.quit() 

上述代码展示了如何在不同网页之间切换,以及进行后退、前进和刷新操作,最后关闭浏览器。

  1. 操作Cookies:Cookies在网页交互中用于存储用户信息等数据,Selenium也能对其进行操作。
python 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

__browser_url = r"D:\Program Files (x86)\360Roaming\360se6\Application\360se.exe" 
chrome_options = Options()
chrome_options.binary_location = __browser_url

driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get('http://www.taobao.com')  
print(driver.get_cookies())
driver.add_cookie({'name': 'zhangsan', 'value' : '98'})
print(driver.get_cookies())

这段代码获取了淘宝网站的Cookies,并添加了一个自定义的Cookie,再次获取Cookies以查看添加效果。

四、项目实战 - 苏宁易购医用口罩信息抓取

下面通过一个实际项目,展示Selenium在数据抓取方面的强大功能。我们要从苏宁易购网站获取医用口罩的价格、名称、评价数和店铺名称信息。

python 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import time

__browser_url = r"D:\Program Files (x86)\360Roaming\360se6\Application\360se.exe" 
chrome_options = Options()
# chrome_options.add_argument('--headless') 
chrome_options.binary_location = __browser_url

driver = webdriver.Chrome(chrome_options = chrome_options)
driver.get('http://www.suning.com')  
element = driver.find_element_by_xpath("//div/input[@tabindex='0']")
element.send_keys("医用口罩" + Keys.RETURN)
time.sleep(20)
driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')
time.sleep(20)
price_elements = driver.find_elements_by_xpath('//span[@class="def-price"]')
title_elements = driver.find_elements_by_xpath('//div[@class="title-selling-point"]')
evaluate_elements = driver.find_elements_by_xpath('//div[@class="info-evaluate"]')
store_elements = driver.find_elements_by_xpath('//div[@class="store-stock"]')
f = open('医用口罩.txt','w',encoding='utf-8')
for i in range(len(price_elements)):
    f.write(price_elements[i].text + '\t')
    f.write(title_elements[i].text + '\t')
    f.write(evaluate_elements[i].text + '\t')
    f.write(store_elements[i].text + '\n')
f.close()

在这个项目中,首先打开苏宁易购网站,通过XPath找到搜索框并输入"医用口罩"进行搜索。然后使用execute_script方法将页面滚动到底部,以便加载更多商品信息。接着,通过XPath分别获取价格、名称、评价数和店铺名称的元素,并将这些信息写入文件中。

Selenium为我们提供了丰富的功能,让网页自动化操作和数据抓取变得更加高效便捷。无论是进行网页测试、数据采集还是自动化任务处理,它都是一个不可多得的好帮手。希望通过这篇博客,大家能对Selenium的使用有更深入的了解,在实际项目中充分发挥它的优势。

相关推荐
不念霉运6 小时前
关键领域软件研发如何构建智能知识管理体系?从文档自动化到安全协同的全面升级
运维·安全·自动化
安冬的码畜日常8 小时前
【AI 加持下的 Python 编程实战 2_13】第九章:繁琐任务的自动化(中)——自动批量合并 PDF 文档
人工智能·python·自动化·ai编程·ai辅助编程
JAVA学习通9 小时前
【测试开发】----自动化测试selenium篇
selenium·测试工具
上官鹿离11 小时前
Selenium教程(Python 网页自动化测试脚本)
python·selenium·测试工具
羸弱的穷酸书生11 小时前
前后端流式交互的几种方式
人工智能·交互·ai编程
梓贤Vigo12 小时前
【Axure高保真原型】中继器表格——自适应高度
交互·产品经理·axure·原型·中继器
mit6.82412 小时前
[自动化Adapt] 父子事件| 冗余过滤 | SQLite | SQLAlchemy | 会话工厂 | Alembic
python·算法·自动化
未来之窗软件服务1 天前
企业自动化交互体系的技术架构与实现:从智能回复到自动评论—仙盟创梦IDE
架构·自动化·交互·仙盟创梦ide·东方仙盟
软件测试-阿涛1 天前
软件测试开发转型经验分享与职业发展指南
经验分享·python·功能测试·ci/cd·自动化·jenkins·持续集成
whabc1001 天前
ubuntu24.04安装selenium、chrome、chromedriver
chrome·selenium·测试工具