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

2022-02-10 14:19:40 浏览数 (2)

代码语言:javascript复制
#-*-coding:utf-8-*-
from selenium import webdriver<br><br>from selenium.webdriver.common.action_chains import ActionChains<br><br>import time,traceback
代码语言:javascript复制
<em>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()<br></em>        ActionChains(driver).click(el).perform()

time.sleep(2)

代码语言:javascript复制
<em id="__mceDel"><em id="__mceDel">        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进程为一直在内存中.
</em></em>

0 人点赞