使用selenium模块自动打开淘宝并进行搜索

Selenium是一个自动化测试工具,可以驱动浏览器器执行特定的动作,如点击,下拉等。可以用来进行模拟人工操作浏览器进行测试,爬虫等。
如果没有安装环境可以先pip install Selenium,同时根据浏览器版本(在帮助或设置可以查看)在
[http://chromedriver.storage.googleapis.com/index.html]中可以下载驱动
例如下图,浏览器版本安装chromedriver_win32.zip即可。具体浏览器可以参考https://blog.csdn.net/huilan_same/article/details/51896672
使用selenium模块自动打开淘宝并进行搜索_第1张图片
,然后解压,任意放在一个路径下在程序中将路径与文件名注明即可使用。
以下是自动打开淘宝并进行搜索结果的代码

from selenium import webdriver
from time import sleep
chromedriver_path =r'F:\anapython\chromedriver'
#实例化一个浏览器对象(传入浏览器的驱动)
bro = webdriver.Chrome(executable_path=chromedriver_path)  #打开浏览器

bro.get('https://uland.taobao.com/sem/tbsearch?')
#定位标签
search_input = bro.find_element_by_id('J_search_key')
#标签交互
search_input.send_keys('华为')
#执行一组js程序
bro.execute_script('window.scrollTo(0,document.body.scrollHeight)')  #向下拖动滚轮
sleep(3)
btn = bro.find_element_by_class_name('submit')  #找到搜索按钮
# btn = bro.find_element_by_css_selector('.submit')  #与上一行效果相同
btn.click()  #点击搜索按钮
sleep(5)
# bro .get('https://www.baidu.com')
# sleep(5)
# bro.quit()  #关闭浏览器

效果图如下:
使用selenium模块自动打开淘宝并进行搜索_第2张图片

你可能感兴趣的:(Python,学习记录)