一.概述
1.
2.安装chromedriver
二.简单操作
案例一:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
# chromedriver.exe路径
path = r'E:\chromedriver_win32\chromedriver.exe'
# 创建chrome浏览器驱动,无头模式)
chrome_options = Options()
chrome_options.add_argument('--headless')
browser = webdriver.Chrome(executable_path=path, options=chrome_options)
# 打开百度
url = 'http://www.baidu.com/'
browser.get(url)
time.sleep(3)
# 截图并保存
browser.save_screenshot('baidu.png')
# 打印页面标题 "百度一下,你就知道"
print(browser.title)
# 关闭浏览器
browser.quit()
案例二: 每一步都实现截图
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
# chromedriver.exe路径
path = r'E:\chromedriver_win32\chromedriver.exe'
# 创建chrome浏览器驱动,无头模式)
chrome_options = Options()
chrome_options.add_argument('--headless')
browser = webdriver.Chrome(executable_path=path, options=chrome_options)
# 打开百度
url = 'http://www.baidu.com/'
browser.get(url)
time.sleep(3)
# 截图
browser.save_screenshot('baidu.png')
# 查找输入框
my_input = browser.find_element_by_id('kw')
# 在输入框输入文字
my_input.send_keys('窗花图片')
#截图
browser.save_screenshot('窗花.png')
# 搜索按钮
button = browser.find_element_by_id('su')
# 点击按钮
button.click()
time.sleep(3)
# 截图
browser.save_screenshot('图片.png')
# 关闭浏览器
browser.quit()
三.下拉滚动条到底部(豆瓣)
在浏览器中搜索豆瓣电影
python代码:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
# chromedriver.exe路径
path = r'E:\chromedriver_win32\chromedriver.exe'
# 创建浏览器驱动(无头模式)
chrome_options = Options()
chrome_options.add_argument('--headless')
browser = webdriver.Chrome(executable_path=path,options=chrome_options)
# 豆瓣url
url = 'https://movie.douban.com/typerank?type_name=%E7%88%B1%E6%83%85&type=13&interval_id=100:90&action='
browser.get(url)
time.sleep(2)
# 让浏览器执行简单的js代码,模拟滚动到底部(只滚动一次,所以得到的电影信息有40条)
js = "window.scrollTo(0,document.body.scrollHeight)" # 还有几种滚动方式,可以自学习一下
browser.execute_script(js)
time.sleep(3)
# 截图
browser.get_screenshot_as_file('douban2.png')
# 获取网页的代码,保存在文件中
html = browser.page_source
with open(r'douban.html', 'w', encoding='utf8') as fp:
fp.write(html)
# 关闭浏览器
browser.quit()
来源:CSDN
作者:独听钟声晚
链接:https://blog.csdn.net/weixin_44321116/article/details/104259843