|
2 | 2 | import logging
|
3 | 3 | import os
|
4 | 4 | import sys
|
| 5 | +import browser_cookie3 |
5 | 6 | from datetime import datetime
|
| 7 | +import json |
6 | 8 |
|
7 | 9 | logger = logging.getLogger('spider.config_util')
|
8 | 10 |
|
@@ -172,3 +174,29 @@ def add_user_uri_list(user_config_file_path, user_uri_list):
|
172 | 174 | user_uri_list[0] = '\n' + user_uri_list[0]
|
173 | 175 | with codecs.open(user_config_file_path, 'a', encoding='utf-8') as f:
|
174 | 176 | f.write('\n'.join(user_uri_list))
|
| 177 | + |
| 178 | +def get_cookie(): |
| 179 | + """Get weibo.cn cookie from Chrome browser""" |
| 180 | + try: |
| 181 | + chrome_cookies = browser_cookie3.chrome(domain_name='weibo.cn') |
| 182 | + cookies_dict = {cookie.name: cookie.value for cookie in chrome_cookies} |
| 183 | + cookie_string = '; '.join(f'{name}={value}' for name, value in cookies_dict.items()) |
| 184 | + return cookie_string |
| 185 | + except Exception as e: |
| 186 | + logger.error(u'Failed to obtain weibo.cn cookie from Chrome browser: %s', str(e)) |
| 187 | + raise |
| 188 | + |
| 189 | +def update_cookie_config(user_config_file_path): |
| 190 | + "Update cookie in config.json" |
| 191 | + if not user_config_file_path: |
| 192 | + user_config_file_path = os.getcwd() + os.sep + 'config.json' |
| 193 | + try: |
| 194 | + cookie = get_cookie() |
| 195 | + with codecs.open(user_config_file_path, 'r', encoding='utf-8') as f: |
| 196 | + config = json.load(f) |
| 197 | + config['cookie'] = cookie |
| 198 | + with codecs.open(user_config_file_path, 'w', encoding='utf-8') as f: |
| 199 | + json.dump(config, f, indent=4, ensure_ascii=False) |
| 200 | + except Exception as e: |
| 201 | + logger.error(u'Failed to update cookie in config file: %s', str(e)) |
| 202 | + raise |
0 commit comments