使用selenium访问爱奇艺网站

使用selenium访问爱奇艺网站

selenium 是一种常用的自动化测试工具。它支持各种浏览器,包括 Chrome,Safari,Firefox 等主流界面式浏览器,如果你在这些浏览器里面安装一个 Selenium 的插件,还可以通过录制,快速生成脚本。

selenium 支持多种主流的开发语言,比如Rubyjavapythonjavascript

环境搭建

python3.7.3

运行 pip install selenium 就可以直接下载最新的selenium版本

准备

浏览器:chrome 70.0.3538.77

操作系统:win7

selenium版本: 3.14.1

chromedriver: https://npm.taobao.org/mirrors/chromedriver/70.0.3538.97/

使用selenium 打开和关闭浏览器

1
2
3
4
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.iqiyi.com/")
driver.quit()

定位搜索框

1
2
search_xpath=r"//*[@id='nav_searchboxIn']/input"
driver.find_element_by_xpath(search_xpath).send_keys("复仇者联盟")

点击搜索图片

1
2
search_button=r"//*[@id='nav_searchboxOut']/span"
driver.find_element_by_xpath(search_button).click()

切换tab页

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#导入键盘操作--20190528更新
from selenium.webdriver.common.keys import Keys
#此处通过键盘操作切换tab页
driver.find_element_by_tag_name("body").send_keys(Keys.CONTROL + "t")
#all_handles 保存所有已经打开的tab窗体
all_handles = driver.window_handles
print(driver.window_handles)
index_handle=driver.current_window_handle
print(index_handle)
#用switch_to方法切换到tab窗体
for handle in all_handles:
if handle!=index_handle:
print('now is search window')
search_handle = handle
driver.switch_to.window(search_handle)

打印页面的title,并截图

1
2
print(driver.title)
driver.get_screenshot_as_file("aqiyi.png")

总结

本文主要介绍了自动化工具selenium的基本使用,如何对页面元素进行基本操作,实现自动抓取关键字图片功能。

坚持原创技术分享,您的支持将鼓励我继续创作!
0%