Code前端首页关于Code前端联系我们

Python的selenium实现了网站自动化和自动索引

terry 2年前 (2023-09-24) 阅读数 60 #后端开发

例如,一个购物网站使用selenium和Python在首页搜索商品,并将爬虫保存在本地Excel表格中。

1。 Python环境和Selenium环境安装

从官网下载并安装python并设置环境变量。

Selenium 通过命令行安装,pip install selenium。 python和selenium都推荐使用3.0版本

从这里使用Chrome浏览器,下载对应Chrome版本的webdriver,并将webdriver放在Python根目录下。

Python之selenium实现网页自动化和自动爬虫

申请产品

时,请使用以下方法检查 Chrome 浏览器版本:帮助 - 关于 Google Chrome (G)

Python之selenium实现网页自动化和自动爬虫

。搜索按钮发送

使用selenium库、time库(sleep用于等待)和xlwt(用于保存excel表格)

 1 from selenium import  webdriver
 2 from time import sleep
 3 import xlwt
 4 #打开浏览器,这里用的chrome
 5 d=webdriver.Chrome()
 6 #设置窗口最大化
 7 d.maximize_window()
 8 #设置隐式等待
 9 d.implicitly_wait(30)
10 #打开网页
11 d.get("https://www.jd.com/")
12 #使用元素定位id找到搜索框
13 d.find_element_by_id("key").send_keys("洗发水")
14 #使用xpath定位到搜索按钮
15 d.find_element_by_xpath("/html/body/div[1]/div[4]/div/div[2]/div/div[2]/button").clic

Python之selenium实现网页自动化和自动爬虫

3.元素的放置,找到匹配的数据,并保存

1 # 初始化excel表格

 2 excel=xlwt.Workbook(encoding="utf-8")
 3 #增加sheet页
 4 sheet=excel.add_sheet("sheet1",cell_overwrite_ok=True)
 5 #定义第1行的内容,以及初始化num,用于从第二行开始写入对应的数据
 6 sheet.write(0,0,'序号')
 7 sheet.write(0,1,'商品')
 8 sheet.write(0,2,'价格')
 9 num=1
10 #通过元素定位面找到,在页面上找到对应商品的各个元素位置
11 goods=d.find_elements_by_xpath("/html/body/div[6]/div[2]/div[2]/div[1]/div/div[2]/ul/li")
12 sleep(5)
13 for good in goods:
14     #分别找到商品与价格所在的元素,并且取其中的文本信息,并去空行
15     price=good.find_element_by_xpath("div/div[3]/strong").text.replace("\n","-")
16     goodtext=good.find_element_by_xpath("div/div[4]/a/em").text.replace("\n","-")
17     sheet.write(num,0,num)
18     sheet.write(num,1,goodtext)
19     sheet.write(num,2,price)
20     num+=1
21     #print(goodtext,"|",price)
22 #保存至excel表
23 excel.save(r"C:\Users\Mr.White\Desktop\test001\jd.xls")
24 #页面退出
25 d.quit()

Python之selenium实现网页自动化和自动爬虫

4.结果预览与总结

Python之selenium实现网页自动化和自动爬虫

1.自动化网页最重要的难点是元素的定位。元素的放置稍后会介绍

2. 页面 可能当用户界面的代码发生变化时,运行的脚本就会失效,维护成本就变得一定。设计合理的自动化脚本变得更加重要。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门