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

 
 
#安装: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)

 
 

猜你喜欢

转载自blog.csdn.net/zbrj12345/article/details/80347878
今日推荐