0%

python selenium自动化操作社交媒体

读取cookie,判断cookie的有效性,定时操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import time
from time import sleep
import requests
import json
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

urlsocial = "" #loginurl
urlLocal = '' #Requesturl

def init_browser():
# path = r'C:/MyEnv/chromedriver.exe '
# ser = Service(path)
PROXY = "socks5://127.0.0.1:1080"
print("----------- start loading browser data ------------")
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
# chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument('lang=zh-CN')
chrome_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36')
chrome_options.add_argument("disable-blink-features=AutomationControlled")
chrome_options.add_argument("disable-infobars")
chrome_options.add_experimental_option('useAutomationExtension', False)
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
chrome_options.add_argument('blink-settings=imagesEnabled=false')
prefs = {
'profile.default_content_setting_values': {
'images': 2,
'notifications': 2
}
}
prefs["credentials_enable_service"] = False
prefs["profile.password_manager_enabled"] = False
chrome_options.add_experimental_option("prefs", prefs)
browser = webdriver.Chrome(options=chrome_options)
# browser = webdriver.Chrome(service=ser, options=chrome_options)
browser.maximize_window()
browser.get(urlsocial)
return browser

def check_cookies(driver):
driver.get(urlLocal)
response = driver.find_element_by_xpath('//*[contains(text(),"Anything")]')
if response:
print("cookie is OK")
return True
else:
print("cookie is bad")
print("res:",response)
get_cookies(driver)
return False

def get_cookies(driver):
driver.get(urlsocial)
time.sleep(5)
driver.find_element_by_xpath('//*[@id="user_email"]').send_keys('your_email')
driver.implicitly_wait(1)
driver.find_element_by_xpath('//*[@id="user_password"]').send_keys('your_password')
driver.implicitly_wait(1) # seconds
driver.find_element_by_xpath('//*[@id="user_password"]').send_keys(Keys.RETURN)
time.sleep(5)
Cookies = driver.get_cookies()
jsCookies = json.dumps(Cookies)
with open('cookies.txt', 'w') as f:
f.write(jsCookies)
print('cookies already writed')

def read_cookies():
with open('cookies.txt', 'r', encoding='utf8') as f:
Cookies = json.loads(f.read())
cookies = []
for cookie in Cookies:
cookie_dict = {
'domain': '.liker.social',
'name': cookie.get('name'),
'value': cookie.get('value'),
'expires': '',
'path': '/',
'httpOnly': False,
'HostOnly': False,
'Secure': False
}
cookies.append(cookie_dict)
return cookies

def login(driver):
cookies = read_cookies()
for cookie in cookies:
driver.add_cookie(cookie)
time.sleep(3)
driver.refresh()
check_cookies(driver)

def operate(browser):
try:
browser.get(urlLocal)
time.sleep(5)
js = "return action=document.body.scrollHeight"
height = browser.execute_script(js)
browser.execute_script('window.scrollTo(0,document.body.scrollHeight)')
sleep(5)
# ...any operation
except WebDriverException as e:
print("not find element 1111", e)
except AssertionError as e:
print("no exist keyword 0000")
except Exception as e:
print(e)
finally:
# print(browser.page_source)
browser.quit()
print('---------end---------------')

if __name__ == '__main__':
while True:
try:
print('start')
driver = init_browser()
# get_cookies(driver)
login(driver)
operate(driver)
sleeptime = random.randrange(18000, 24000)
time.sleep(sleeptime)
except:
pass
continue