引入概述
# 能不能让我的程序连接到浏览器 . 让浏览器来完成各种复杂的操作, 我们只接受最终的结果
# selenium: 自动化测试工具
# 可以: 打开浏览器. 然后像人一样去操作浏览器
# 程序员可以从selenium中直接提取网页上的各种信息
# 环境搭建:
# pip install selenium -i 清华源
# 下载浏览器驱动:https://npm.taobao.org/mirrors/chromedriver
# 把解压缩的浏览器驱动 chromedriver 放在python解释器所在的文件夹
# 让selenium启动谷歌浏览器
from selenium.webdriver import Chrome
# 1.创建浏览器对象
web = Chrome()
# 2.打开一个网址
web.get("http://www.baidu.com")
print(web.title)
各种操作
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
import time
web = Chrome()
web.get("http://lagou.com")
# 找到某个元素. 点击它
el = web.find_element_by_xpath('//*[@id="changeCityBox"]/ul/li[1]/a')
el.click() # 点击事件
time.sleep(1) # 让浏览器缓一会儿
# 找到输入框. 输入python => 输入回车/点击搜索按钮
web.find_element_by_xpath('//*[@id="search_input"]').send_keys("python", Keys.ENTER)
time.sleep(1)
# 查找存放数据的位置. 进行数据提取
# 找到页面中存放数据的所有的li
li_list = web.find_elements_by_xpath('//*[@id="s_position_list"]/ul/li')
for li in li_list:
job_name = li.find_element_by_tag_name("h3").text
job_price = li.find_element_by_xpath("./div/div/div[2]/div/span").text
company_name = li.find_element_by_xpath('./div/div[2]/div/a').text
print(company_name, job_name, job_price)
窗口切换
# # 在新窗口中提取内容
# job_detail = web.find_element_by_xpath('//*[@id="job_detail"]/dd[2]/div').text
# print(job_detail)
#
# # 关掉子窗口
# web.close()
# # 变更selenium的窗口视角. 回到原来的窗口中
# web.switch_to.window(web.window_handles[0])
# print(web.find_element_by_xpath('//*[@id="s_position_list"]/ul/li[1]/div[1]/div[1]/div[1]/a/h3').text)
# 如果页面中遇到了 iframe如何处理
web.get("https://www.91kanju.com/vod-play/541-2-1.html")
# 处理iframe的话. 必须先拿到iframe. 然后切换视角到iframe . 再然后才可以拿数据
iframe = web.find_element_by_xpath('//*[@id="player_iframe"]')
web.switch_to.frame(iframe) # 切换到iframe
# web.switch_to.default_content() # 切换回原页面
tx = web.find_element_by_xpath('//*[@id="main"]/h3[1]').text
print(tx)
无头浏览器
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.select import Select
import time
# 准备好参数配置
opt = Options()
opt.add_argument("--headless")
opt.add_argument("--disbale-gpu")
web = Chrome(options=opt) # 把参数配置设置到浏览器中
web.get("https://www.endata.com.cn/BoxOffice/BO/Year/index.html")
time.sleep(2)
# # 定位到下拉列表
# sel_el = web.find_element_by_xpath('//*[@id="OptionDate"]')
# # 对元素进行包装, 包装成下拉菜单
# sel = Select(sel_el)
# # 让浏览器进行调整选项
# for i in range(len(sel.options)): # i就是每一个下拉框选项的索引位置
# sel.select_by_index(i) # 按照索引进行切换
# time.sleep(2)
# table = web.find_element_by_xpath('//*[@id="TableList"]/table')
# print(table.text) # 打印所有文本信息
# print("===================================")
#
# print("运行完毕. ")
# web.close()
# 如何拿到页面代码Elements(经过数据加载以及js执行之后的结果的html内容)
print(web.page_source)