python使用selenium模拟操作Chrome浏览器,cookie的生成与读取

#-*-coding:utf-8-*-
from selenium import webdriver

from selenium.webdriver.common.action_chains import ActionChains

import time,traceback
import json,os

driver = webdriver.Chrome()     # 创建Chrome对象.
driver.maximize_window()
# 操作这个对象.
driver.get('https://mp.toutiao.com/')     # get方式访问
time.sleep(5)

if os.path.exists('ttcookie.txt'):
    fr=open('ttcookie.txt','r')
    cookielist=json.load(fr)
    fr.close()
    for cookie in cookielist:
        driver.add_cookie(cookie)
    driver.get('https://mp.toutiao.com/')   
else:
    #获取网站cookie
    diccookie=driver.get_cookies()
    fw=open('ttcookie.txt','w')
    json.dump(diccookie,fw)
    fw.close()
time.sleep(5)
#滚动到浏览器顶部
js_top = "var q=document.documentElement.scrollTop=0"
#滚动到浏览器底部
js_bottom = "var q=document.documentElement.scrollTop=10000"
js_bottom2 = "window.scrollTo(0,document.body.scrollHeight)"

driver.execute_script(js_top)

el = driver.find_element_by_link_text("作品管理")
el.click()
time.sleep(2)

el = driver.find_elements_by_class_name('byte-tabs-header-title')[1]
el.click()
time.sleep(2)

for i in range(1,1000):
    try:
        el = driver.find_element_by_xpath('//div[@class="action-content"]/div[4]')
        #el.click()
ActionChains(driver).click(el).perform()
                    time.sleep(2)
        el = driver.find_element_by_xpath('//div[@class="more-content"]/div[5]')
        el.click()
        time.sleep(2)
        el = driver.find_element_by_xpath('//div[@class="byte-modal-footer"]/button[2]')
        el.click()
        print('byte-modal-footer')
        time.sleep(10)
        #driver.refresh()
    except Exception:
        traceback.print_exc()
        pass
#print(txt)
#driver.get_screenshot_as_file('foo.png')
time.sleep(10)
driver.quit()   # 使用完, 记得关闭浏览器, 不然chromedriver.exe进程为一直在内存中.

  

posted @ 2020-08-27 11:10  凉城  阅读(1438)  评论(0编辑  收藏  举报