Python3-爬虫~selenium\phantomjs\ActionChains百度例子

40 篇文章 0 订阅
10 篇文章 0 订阅
 
#安装:pip install selenium=2.48.0
#显示:pip show selenium
#卸载:pip uninstall selenium

#模拟用户行为
import os,time
from selenium import webdriver,common
import selenium
from selenium.webdriver.common.action_chains import ActionChains
#用selenium做自动化,有时候会遇到需要模拟鼠标操作才能进行的情况,
# 比如单击、双击、点击鼠标右键、拖拽等等。而selenium给我们提供了一个类来处理这类事件——ActionChains
#浏览器
driver=webdriver.PhantomJS()


#访问
driver.get('https://www.baidu.com/')

#截屏
root_dir='baidu'
if not os.path.exists(root_dir):
    os.mkdir(root_dir)
    
file_name=root_dir+'/homepage.png'
driver.save_screenshot(file_name)

#模拟用户行为操作
#输入行为
timeout=4
count=0
while True:
    try:
        if count>4:
            break
        obj=driver.find_element_by_id('kw')
        # print(obj)
        #发送关键字
        obj.send_keys(u'章子怡')#若出现编码问题字符串前加"u",表示unicode码
        break
    except common.exceptions.NoSuchAttributeException as e:
        print(e)
        time.sleep(timeout)
        count+=1
        
file_name=root_dir+'/zhangziyi.png'
driver.save_screenshot(file_name)
'''
    try:
        obj = driver.find_element_by_id("kw")
        obj.send_keys(u"章子怡")
        print(obj)
        break
    except common.exceptions.NoSuchElementException as e:
        print(e)
'''
#点击搜索
'''
#报错代码:selenium.common.exceptions.ElementNotVisibleException
su=driver.find_element_by_id('su')
su.click()
file_name2=root_dir+'/zhangziyi2.png'
driver.save_screenshot(file_name2)
'''
driver.execute_script("$('#su').eq(0).attr('style','height:20px;opacity:1;display:block;position:static;transform:translate(0px, 0px) scale(1)')")
click_btn=driver.find_element_by_id('su')
# su.click()
ActionChains(driver).click(click_btn).click()
time.sleep(5) #以免网络慢(超时)没能取到元素
file_name2=root_dir+'/zhangziyi2.png'
driver.save_screenshot(file_name2)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值