山东大学暑期实训-饮食健康管理系统设计与实现(五)
selenium初探
环境准备
本篇博客建立在已经安装好python、selenium、chromedriver的基础上,探索它们的基本使用。
第一步 新建一个项目
新建项目
第二步 导入需要用到的python模块
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import warnings
warnings.filterwarnings("ignore")
第三步 根据chromedriver创建驱动
driver = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe")
这里的executable_path是我们安装好的chromedriver的地址
第四步 确定url及用driver访问url
也可以选择给driver配置参数,比如下面就配置chrome使用无头浏览器访问。
chrome_options = Options()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe", options=chrome_options)
url = "https://home.meishichina.com/"
driver.get(url)
第五步 捕获截取想要的数据
selenium为获取数据提供了许多好用的api,下面是几个常用的
driver.find_element_by_id() # 根据id寻找唯一一个
driver.find_element_by_class_name() # 根据class找第一个
driver.find_elements_by_class_name() # 根据class找一个列表
driver.find_element_by_name() # 根据name属性找一个
driver.find_element_by_css_selector() # 根据css选择器找,这是很强大的一个
driver.find_element_by_link_text() # 根据链接文本的内容找
driver.find_element_by_xpath() # 根据xpath路径找,这也是很常用很强大的一个
第六步 对获取到的数据做处理
根据上一步我们捕获到的数据,根据自己的需求,做数据处理或数据持久化。
第七步 关闭驱动及浏览器
driver.quit()
driver.close()