以登录清博大数据举例,登录后需要把cookie存本地,每次跑selenium时候就用谷歌跑:
#清博账号登录以及保存cookie
class Qingbo():
url = 'http://www.gsdata.cn/member/login'
def __init__(self):
self.data_path = cookie_path
if not os.path.exists('cookie'):
os.makedirs(self.data_path)
cap = webdriver.DesiredCapabilities.PHANTOMJS
cap["phantomjs.page.settings.resourceTimeout"] = 1000
# self.driver = webdriver.PhantomJS(desired_capabilities=cap)
self.driver = webdriver.Chrome()
self.driver.set_page_load_timeout(30)
def __del__(self):
self.driver.quit()
def save_cookie_to_file(self):
cookies = self.driver.get_cookies()
# print cookies
with codecs.open(cookie_path, mode='w+', encoding='utf-8') as f:
for cookie in cookies:
line = json.dumps(cookie, ensure_ascii=False) + '\n'
f.write(line)
def retry_get(self, url):
for retry in range(3):
try:
self.driver.get(url)
break
except TimeoutException:
self.driver.execute_script('window.stop()')
def login_in(self):
# try:
self.retry_get(self.url)
is_code = self.driver.find_element_by_xpath('//*[@id="wxLogin"]/p')
print(is_code.text)
if u'微信扫一扫' in is_code.text:
user_log_button = self.driver.find_element_by_xpath('/html//div[contains(@class,"login-box")]/div[contains(@class,"login-body")]/a[@class="login-type current"]')
print(user_log_button)
user_log_button.click()
uin_input = self.driver.find_element_by_name('username')
uin_input.clear()
uin_input.send_keys(QINGBO_USERNAME)
pwd_input = self.driver.find_element_by_name("password")
pwd_input.clear()
pwd_input.send_keys(QINGBO_PASSWORD)
pwd_input.send_keys(Keys.ENTER)
self.save_cookie_to_file()
self.__del__()