├── .gitignore ├── LICENSE ├── README.md ├── main.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 zhaoxilingcheng 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jd_maotai rpa 2 | 基于selenium驱动的jd抢购rpa机器人, 照顾我们这样的马大哈, 不会忘记抢购了, 祝大家过年都能喝上茅台. 3 | 4 | ## 特别声明: 5 | 6 | * 本仓库发布的`jd_maotai_rpa`项目定义为自动化rpa项目, 是用于防止忘记参与jd茅台的活动(由于本人时常忘记), 而不是为了秒杀和抢购。 7 | 8 | * 本仓库发布的`jd_maotai_rpa`项目中涉及的任何脚本,仅用于测试和学习研究,禁止用于商业用途,不能保证其合法性,准确性,完整性和有效性,请根据情况自行判断。 9 | 10 | * 本项目内所有资源文件,禁止任何公众号、自媒体进行任何形式的转载、发布。 11 | 12 | * `zhaoxilingcheng` 对任何脚本问题概不负责,包括但不限于由任何脚本错误导致的任何损失或损害. 13 | 14 | * 间接使用脚本的任何用户,包括但不限于建立VPS或在某些行为违反国家/地区法律或相关法规的情况下进行传播, `zhaoxilingcheng` 对于由此引起的任何隐私泄漏或其他后果概不负责。 15 | 16 | * 请勿将`jd_maotai_rpa`项目的任何内容用于商业或非法目的,否则后果自负。 17 | 18 | * 如果任何单位或个人认为该项目的脚本可能涉嫌侵犯其权利,则应及时通知并提供身份证明,所有权证明,我们将在收到认证文件后删除相关脚本。 19 | 20 | * 以任何方式查看此项目的人或直接或间接使用`jd_maotai_rpa`项目的任何脚本的使用者都应仔细阅读此声明。`zhaoxilingcheng` 保留随时更改或补充此免责声明的权利。一旦使用并复制了任何相关脚本或`jd_maotai_rpa`项目,则视为您已接受此免责声明。 21 | 22 | * 您必须在下载后的24小时内从计算机或手机中完全删除以上内容。 23 | 24 | * 本项目遵循`GPL-3.0 License`协议,如果本特别声明与`GPL-3.0 License`协议有冲突之处,以本特别声明为准。 25 | 26 | > ***您使用或者复制了本仓库且本人制作的任何代码或项目,则视为`已接受`此声明,请仔细阅读*** 27 | > ***您在本声明未发出之时点使用或者复制了本仓库且本人制作的任何代码或项目且此时还在使用,则视为`已接受`此声明,请仔细阅读*** 28 | 29 | ## 说明 30 | 我认为直接采用selenium驱动的参与抢购活动更直观, 问题少, 实现简单, 然而不会存在十全十美的办法, 此方式的实现导致抢购速度不如requests请求来的快, 但好在不需要参考太多参数, 不需要一点一点的去抓包分析. 31 | 32 | ## 实现说明 33 | 1. 用户扫码直接登录 34 | 2. 计算jd与本地时差 35 | 3. 提前刷新页面监控字段值 36 | 4. 点击具体的字段值 37 | 5. 如果可以提交订单则提交订单 38 | 6. 否则失败 39 | 40 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import json 2 | import pickle 3 | import random 4 | import time 5 | from abc import ABC, abstractmethod 6 | from datetime import datetime 7 | 8 | import requests 9 | from selenium import common 10 | from selenium import webdriver 11 | from selenium.webdriver.common.by import By 12 | from selenium.webdriver.support.expected_conditions import presence_of_element_located 13 | from selenium.webdriver.support.wait import WebDriverWait 14 | from webdriver_manager.chrome import ChromeDriverManager 15 | 16 | 17 | class Timer(object): 18 | def __init__(self, sleep_interval=0.5, buy_time='09:59:59.500'): 19 | # '2018-09-28 22:45:50.000' 20 | # buy_time = 2020-12-22 09:59:59.500 21 | localtime = time.localtime(time.time()) 22 | 23 | buy_time_config = datetime.strptime( 24 | localtime.tm_year.__str__() + '-' + localtime.tm_mon.__str__() + '-' + localtime.tm_mday.__str__() + ' ' + buy_time, 25 | "%Y-%m-%d %H:%M:%S.%f") 26 | if time.mktime(localtime) < time.mktime(buy_time_config.timetuple()): 27 | self.buy_time = buy_time_config 28 | else: 29 | self.buy_time = datetime.strptime( 30 | localtime.tm_year.__str__() + '-' + localtime.tm_mon.__str__() + '-' + ( 31 | localtime.tm_mday + 1).__str__() + ' ' + buy_time, 32 | "%Y-%m-%d %H:%M:%S.%f") 33 | print("购买时间:{}".format(self.buy_time)) 34 | 35 | self.buy_time_ms = int(time.mktime(self.buy_time.timetuple()) * 1000.0 + self.buy_time.microsecond / 1000) 36 | self.sleep_interval = sleep_interval 37 | 38 | self.diff_time = self.local_jd_time_diff() 39 | 40 | def jd_time(self): 41 | """ 42 | 从京东服务器获取时间毫秒 43 | :return: 44 | """ 45 | url = 'https://a.jd.com//ajax/queryServerData.html' 46 | ret = requests.get(url).text 47 | js = json.loads(ret) 48 | return int(js["serverTime"]) 49 | 50 | def local_time(self): 51 | """ 52 | 获取本地毫秒时间 53 | :return: 54 | """ 55 | return int(round(time.time() * 1000)) 56 | 57 | def local_jd_time_diff(self): 58 | """ 59 | 计算本地与京东服务器时间差 60 | :return: 61 | """ 62 | return self.local_time() - self.jd_time() 63 | 64 | def start(self): 65 | print(f'正在等待到达设定时间:{self.buy_time},本地时间为{self.local_time()}, jd时间为{self.jd_time()},' 66 | f' 检测本地时间与京东服务器时间误差为【{self.diff_time}】毫秒') 67 | wait_time = 1 68 | while True: 69 | # 本地时间减去与京东的时间差,能够将时间误差提升到0.1秒附近 70 | # 具体精度依赖获取京东服务器时间的网络时间损耗 71 | if self.local_time() - self.diff_time >= self.buy_time_ms: 72 | print('时间到达,开始执行……') 73 | break 74 | else: 75 | if wait_time % 100 == 0: 76 | print('正在等待中...', f'还需等待{(self.buy_time_ms - (self.local_time() - self.diff_time)) / 1000}秒') 77 | time.sleep(self.sleep_interval) 78 | wait_time += 1 79 | 80 | 81 | class BaseSpider(ABC): 82 | 83 | def __init__(self, base_url: str, login_url: str, verify_url: str, sleep_time: int = 3): 84 | self.base_url = base_url 85 | self.login_url = login_url 86 | self.verify_url = verify_url 87 | self.driver = self.get_chrome_driver() 88 | self.wait = WebDriverWait(self.driver, 0.3, 0.05) 89 | self.is_login = False 90 | self.sleep_time = sleep_time 91 | self.data_list = [] 92 | 93 | def start(self): 94 | self.login_by_cookies() 95 | self.driver.get(self.base_url) 96 | self.run() 97 | self.close() 98 | 99 | @abstractmethod 100 | def run(self): 101 | pass 102 | 103 | def sleep(self): 104 | time.sleep(self.sleep_time) 105 | 106 | @staticmethod 107 | def get_chrome_driver() -> webdriver: 108 | options = webdriver.ChromeOptions() 109 | options.add_argument('--no-sandbox') 110 | # options.add_argument('--headless') # 无头参数 111 | options.add_argument('--disable-gpu') 112 | # 關閉瀏覽器左上角通知提示 113 | prefs = { 114 | 'profile.default_content_setting_values': 115 | { 116 | 'notifications': 2 117 | } 118 | } 119 | options.add_experimental_option('prefs', prefs) 120 | # 關閉'chrome目前受到自動測試軟體控制'的提示 121 | options.add_experimental_option('useAutomationExtension', False) 122 | options.add_experimental_option('excludeSwitches', ['enable-automation']) 123 | driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=options) 124 | driver.maximize_window() 125 | driver.implicitly_wait(10) 126 | return driver 127 | 128 | def login_by_cookies(self): 129 | if self.load_cookie(): 130 | return self 131 | return self.login() 132 | 133 | def login(self): 134 | print('开始进行人工登录') 135 | driver = self.driver 136 | if not self.is_login: 137 | driver.get(self.login_url) 138 | self.verify_login() 139 | return self 140 | 141 | def verify_login(self): 142 | wait_time = 0 143 | while True and not self.is_login: 144 | print(f'登录中...等待时间为{wait_time}s') 145 | time.sleep(5) 146 | wait_time = wait_time + 5 147 | if self.verify_url in self.driver.current_url and not self.driver.current_url == self.login_url: 148 | print('登录成功') 149 | self.is_login = True 150 | break 151 | if wait_time >= 300: 152 | raise Exception('登录失败') 153 | self.save_cookie() 154 | return self.is_login 155 | 156 | def save_cookie(self): 157 | cookie = self.driver.get_cookies() 158 | with open(self.__class__.__name__, 'wb') as f: 159 | f.write(pickle.dumps(cookie)) 160 | 161 | def load_cookie(self): 162 | print('开始加载cookies信息') 163 | try: 164 | with open(self.__class__.__name__, 'rb') as f: 165 | cookie = pickle.load(f) 166 | if not cookie: 167 | return False 168 | except FileNotFoundError as e: 169 | return False 170 | for cookies in cookie: 171 | if 'expiry' in cookies: 172 | del cookies['expiry'] 173 | if 'domain' in cookie: 174 | del cookies['domain'] 175 | self.driver.get(self.base_url) 176 | for i in cookie: 177 | self.driver.add_cookie(i) 178 | print("load over") 179 | self.driver.refresh() 180 | self.is_login = True 181 | return self 182 | 183 | def close(self): 184 | self.save_cookie() 185 | self.driver.close() 186 | self.driver.quit() 187 | self.is_login = False 188 | 189 | 190 | class JdSpider(BaseSpider): 191 | 192 | def __init__(self, sleep_time: int = 3, item_id: int = 100012043978, buy_time='09:59:50.500'): 193 | super().__init__(base_url='http://jd.com', login_url='https://passport.jd.com/new/login.aspx', 194 | verify_url='https://www.jd.com/', sleep_time=sleep_time) 195 | self.item_id = item_id 196 | self.item_url = f'https://item.jd.com/{item_id}.html' 197 | self.buy_time = buy_time 198 | 199 | def run(self): 200 | self.driver.get(self.item_url) 201 | Timer(buy_time=self.buy_time).start() 202 | try_time = 0 203 | while True: 204 | self.driver.get(self.item_url) 205 | first_result = self.wait.until(presence_of_element_located((By.ID, "btn-reservation"))) 206 | text_content = first_result.get_attribute("textContent") 207 | if text_content in ['等待抢购', '开始预购', '等待预购', '等待预约', '开始预约']: 208 | print('还没开始,等待抢购!') 209 | else: 210 | try_time += 1 211 | try: 212 | print('终于开始了,立即抢购!') 213 | first_result.click() 214 | first_result = self.wait.until(presence_of_element_located((By.CLASS_NAME, "checkout-submit"))) 215 | first_result.click() 216 | print("提交订单!") 217 | time.sleep(30) 218 | break 219 | except common.exceptions.TimeoutException as e: 220 | print(f'第{try_time}次没赶上-----------再试试!!!!!!!') 221 | if try_time >= 30: 222 | print('不试了, 明天再来') 223 | break 224 | if try_time == 0: 225 | time.sleep(random.randint(1, 5) * 0.1) 226 | 227 | 228 | if __name__ == '__main__': 229 | # 提前一直刷新页面 230 | dd = JdSpider(buy_time='09:59:53.500') 231 | dd.start() 232 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests==2.23.0 2 | selenium==3.141.0 3 | webdrivermanager==0.9.0 4 | webdriver_manager==3.2.2 5 | --------------------------------------------------------------------------------