├── categories.ods ├── requirements.txt ├── .gitignore ├── config.json.example ├── README.md ├── LICENSE └── kleinanzeigen.py /categories.ods: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Second-Hand-Friends/ebayKleinanzeigen/HEAD/categories.ods -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | astroid==2.4.2 2 | backports-datetime-fromisoformat==1.0.0 3 | isort==5.6.4 4 | lazy-object-proxy==1.4.3 5 | mccabe==0.6.1 6 | pylint==2.6.0 7 | python-dateutil==2.8.1 8 | selenium==3.141.0 9 | selenium_stealth==1.0.6 10 | six==1.15.0 11 | toml==0.10.2 12 | typed-ast==1.4.1 13 | urllib3==1.26.2 14 | wrapt==1.12.1 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | 59 | config.json 60 | *.jpg 61 | .idea 62 | .DS_Store 63 | 64 | # VSC history extension 65 | .history 66 | # pictures for the ads 67 | data 68 | # default configuration files 69 | config.json 70 | config.jsonc 71 | -------------------------------------------------------------------------------- /config.json.example: -------------------------------------------------------------------------------- 1 | { 2 | "glob_username": "", 3 | "glob_password": "", 4 | "glob_street": "", 5 | "glob_zip": "", 6 | "glob_contact_name": "", 7 | "glob_phone_number": "", 8 | "glob_photo_path": "/path/to/photos/", 9 | "glob_ad_prefix": "Text to add which comes before the actual ad description.\nLeave free if not needed\n", 10 | "glob_ad_suffix": "Text to add which comes after the actual ad description.\nLeave free if not needed\n", 11 | "webdriver_enabled": false, 12 | "update_interval": 30, // number of days an ad has to be old in order to be reposted 13 | "ads": [ 14 | { 15 | "type": "OFFER", 16 | "title": "Example 1", 17 | "desc": "... with a negotiable price (5 EUR) and some photos.", 18 | "enabled": "1", 19 | "price": "5", 20 | "price_type": "NEGOTIABLE", 21 | "caturl": "https://www.ebay-kleinanzeigen.de/p-kategorie-aendern.html#?path=80/88/sofas_sitzgarnituren&isParent=false", 22 | "shipping_type": "PICKUP", 23 | "photofiles": [ "file1.jpg", "file2.jpg" ], 24 | "zip" : "33333" 25 | }, 26 | { 27 | "type": "WANTED", 28 | "title": "Example 2", 29 | "description_file" : "/abspath/to/file.txt", // will not read contents of "desc" 30 | "enabled": "1", 31 | "price": "10", 32 | "shipping_type": "SHIPPING", 33 | "price_type": "FIXED", 34 | "caturl": "https://www.ebay-kleinanzeigen.de/p-kategorie-aendern.html#?path=80/88/sofas_sitzgarnituren&isParent=false", 35 | "photo_dir": "folder_name/or/subdirectory/with/images/", 36 | "additional_category_options": { 37 | "foto.art_s": "Zubehör", 38 | "foto.condition_s": "Gebraucht" 39 | } 40 | }, 41 | ] 42 | } 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > Development of this client has been stopped. Please use https://github.com/Second-Hand-Friends/kleinanzeigen-bot 2 | 3 | # ebayKleinanzeigen 4 | 5 | ## Prerequisites 6 | 7 | * Python 3 and pip 8 | * Chrome or Chromium 9 | * ChromeDriver for your specific Chrome/Chromium version 10 | 11 | ## Features 12 | 13 | * Upload all images from a set subdirectory 14 | * Configure shipping type in ad config 15 | * Automatically deletes and re-publishes ad if existing one is too old 16 | * Keeps track of ad publishing and last updating date 17 | * Ability to selectively enable / disable ads being published / updated 18 | * Overrides auto detected category (if `caturl` is specified) and fills the form data 19 | * Uploads multiple photos 20 | 21 | ## Installation Guide (Linux) 22 | 23 | 1. Install Python 3 and PIP: 24 | `sudo apt install python3 python3-pip` 25 | 2. Clone the app from git and switch into the newly created directory: 26 | `git clone https://github.com/donwayo/ebayKleinanzeigen && cd ebayKleinanzeigen` 27 | 3. Install required packages: 28 | `pip3 install -r requirements.txt` 29 | 4. Install Chromium **(skip this step if you have Chrome or Chromium installed already)**: 30 | `sudo apt install chromium-browser` 31 | 5. Install ChromeDriver: 32 | `sudo apt install chromium-chromedriver` 33 | Or, if your version of Chrome/Chromium does not automatically update, download the corresponding [ChromeDriver](https://chromedriver.chromium.org/downloads) for your installed version. Then extract the binary into the ebayKleinanzeigen directory and don't forget `chmod +x chromedriver`. 34 | 6. Configure the app: 35 | * Copy the sample to a new file: 36 | `cp config.json.example config.json` 37 | * Edit the file and fill in your details. 38 | * To find out the categories you need to start posting an ad on the website and then copy the corresponding link to the category from there. It's the screen where you select the category. 39 | 7. To run the app, run `python3 kleinanzeigen.py --profile config.json` 40 | If launching from VS Code, the following path variable should be set when not in headless mode: 41 | `export DISPLAY=":0"` ([source](https://stackoverflow.com/a/61672397/256002)) 42 | 43 | Now a browser window should start, login and fill the fields automatically. 44 | 45 | ## Installation Guide (MacOS) 46 | 47 | 1. Install a specific version of Chromium from https://chromium.cypress.io/mac/ 48 | 2. Add the executable to the `PATH` 49 | 3. Run these steps: 50 | ```zsh 51 | brew install chromedriver 52 | 53 | # create new virtual env, for instance with conda 54 | conda create --name ebayKleinanzeigen python=3.7 55 | conda activate ebayKleinanzeigen 56 | 57 | git clone https://github.com/donwayo/ebayKleinanzeigen 58 | cd ebayKleinanzeigen 59 | pip3 install -r requirements.txt 60 | 61 | cp config.json.example config.json 62 | ``` 63 | 4. Open config.json and enter your preferences. For cat_url, see below 64 | To find out the categories you need to start posting an ad on the website and then copy the corresponding link to the category from there. It's the screen where you select the category. 65 | 5. To run the app, run `python kleinanzeigen.py --profile config.json` 66 | 67 | Now a browser window should start, login and fill the fields automatically. 68 | 69 | ## Installation Guide (Windows) 70 | 71 | 1. Install Python 3 from [here](https://www.python.org/downloads/) or from the Windows 10 App Store 72 | 2. Download the latest ebayKleinanzeigen version via `git clone https://github.com/donwayo/ebayKleinanzeigen.git && cd ebayKleinanzeigen` 73 | Or, if you don't have git installed, as a zip from [here](https://github.com/donwayo/ebayKleinanzeigen/archive/refs/heads/master.zip) and extract it, then open the extracted directory. 74 | 3. Open a command prompt (CMD, PowerShell or Git Bash) inside the ebayKleinanzeigen directory, then install the required Python packages: 75 | `python3 -m pip3 install -r requirements.txt` 76 | 4. Install Chrome for Windows 77 | Or, if you don't want to install Chrome, download the latest version of Chromium from [here](https://download-chromium.appspot.com/) and copy the number after "Build Revision: " to your clipboard without leading or trailing whitespaces for the next step. Extract the zip and copy the `chrome-win` folder over to the ebayKleinanzeigen directory. 78 | 5. Download ChromeDriver for your version of Chrome from [here](https://chromedriver.chromium.org/downloads) 79 | In case of Chromium, you can get it by replacing the `BUILD_REVISION` in this link with the number you just copied in the last step: `https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Win/BUILD_REVISION/`. The archive you need to download is named chromedriver_win32.zip. 80 | 6. Extract and copy chromedriver.exe to the ebayKleinanzeigen directory 81 | 7. Configure the app 82 | * Copy `config.json.example` to a new file named `config.json` 83 | * Edit `config.json` and fill in your details 84 | * To find out the categories you need to start posting an ad on the website and then copy the corresponding link to the category from there. It's the screen where you select the category. 85 | 8. To run the app, run `python3 kleinanzeigen.py --profile config.json` in the command prompt. 86 | 87 | Now a browser window should start, login and fill the fields automatically. 88 | 89 | ## Additional Category fields 90 | 91 | | | | | 92 | |---|---| ---| 93 | | Elektronik > Foto | `foto.art_s` | `Kamera`, `Objektiv`, `Zubehör`, `Kamera & Zubehör` | 94 | | Elektronik > Foto | `foto.condition_s` | `Neu`, `Gebraucht`, `Defekt` | 95 | 96 | ## Credits 97 | 98 | * @Lopp0 - initial script 99 | * @donwayo - Fixes and improvements 100 | * @MichaelKueller - Python 3 migration and cleanup 101 | * @n3amil - Fixes and improvements 102 | * @x86dev - Fixes and improvements 103 | * @neon-dev - Fixes and improvements 104 | * @kahironimashte - Install guide 105 | * @therealsupermario - Description Files, ad-level zip codes, custom update interval, support for additional category fields 106 | * @denisergashbaev - python 3.6 fixes, README.md, running from VS Code 107 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /kleinanzeigen.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # pylint: disable=C0301 4 | # pylint: disable=C0111 5 | 6 | """ 7 | Created on Tue Oct 6 00:15:14 2015 8 | Updated and improved by x86dev Dec 2017. 9 | 10 | @author: Leo; Eduardo; x86dev 11 | """ 12 | import getopt 13 | import json 14 | import logging 15 | import os 16 | import signal 17 | import sys 18 | import time 19 | import urllib.parse 20 | from datetime import datetime 21 | from platform import python_version_tuple 22 | from random import randint 23 | 24 | from selenium import webdriver 25 | from selenium.common.exceptions import NoSuchElementException 26 | from selenium.webdriver.common.by import By 27 | from selenium.webdriver.common.keys import Keys 28 | from selenium.webdriver.support import expected_conditions as EC 29 | from selenium.webdriver.support.ui import Select, WebDriverWait 30 | from selenium_stealth import stealth 31 | 32 | log = logging.getLogger(__name__) 33 | log.setLevel(logging.DEBUG) 34 | fh = logging.FileHandler('kleinanzeigen.log') 35 | fh.setLevel(logging.DEBUG) 36 | 37 | ch = logging.StreamHandler() 38 | ch.setLevel(logging.DEBUG) 39 | 40 | formatter = logging.Formatter('%(asctime)s %(message)s') 41 | 42 | log.addHandler(ch) 43 | log.addHandler(fh) 44 | 45 | 46 | def profile_read(profile, config): 47 | if os.path.isfile(profile): 48 | with open(profile, encoding="utf-8") as file: 49 | config.update(json.load(file)) 50 | 51 | 52 | def profile_write(profile, config): 53 | with open(profile, "w+", encoding='utf8') as fh_config: 54 | text = json.dumps(config, sort_keys=True, indent=4, ensure_ascii=False) 55 | fh_config.write(text) 56 | 57 | 58 | def login(config): 59 | input_email = config['glob_username'] 60 | input_pw = config['glob_password'] 61 | log.info("Login with account email: " + input_email) 62 | driver.get('https://www.ebay-kleinanzeigen.de/m-einloggen.html') 63 | 64 | # wait for the 'accept cookie' banner to appear 65 | WebDriverWait(driver, 6).until(EC.element_to_be_clickable((By.ID, 'gdpr-banner-accept'))).click() 66 | 67 | text_area = WebDriverWait(driver, 1).until(EC.presence_of_element_located((By.ID, 'login-email'))) 68 | text_area.send_keys(input_email) 69 | fake_wait(200) 70 | 71 | text_area = driver.find_element_by_id('login-password') 72 | text_area.send_keys(input_pw) 73 | fake_wait(200) 74 | 75 | submit_button = driver.find_element_by_id('login-submit') 76 | submit_button.click() 77 | 78 | 79 | def fake_wait(ms_sleep=None): 80 | if ms_sleep is None: 81 | ms_sleep = randint(600, 2000) 82 | if ms_sleep < 100: 83 | ms_sleep = 100 84 | log.debug("Waiting %d ms ..." % ms_sleep) 85 | time.sleep(ms_sleep / 1000) 86 | 87 | 88 | def delete_ad(driver, ad): 89 | log.info("\tDeleting ad ...") 90 | 91 | driver.get("https://www.ebay-kleinanzeigen.de/m-meine-anzeigen.html") 92 | fake_wait() 93 | 94 | ad_id_elem = None 95 | 96 | if "id" in ad: 97 | try: 98 | ad_id_elem = driver.find_element_by_xpath("//a[@data-adid='%s']" % ad["id"]) 99 | except NoSuchElementException: 100 | log.info("\tNot found by ID") 101 | 102 | if ad_id_elem is None: 103 | try: 104 | ad_id_elem = driver.find_element_by_xpath("//a[contains(text(), '%s')]/../../../../.." % ad["title"]) 105 | except NoSuchElementException: 106 | log.info("\tNot found by title") 107 | 108 | if ad_id_elem is not None: 109 | try: 110 | btn_del = ad_id_elem.find_elements_by_class_name("managead-listitem-action-delete")[1] 111 | btn_del.click() 112 | 113 | fake_wait() 114 | 115 | btn_confirm_del = driver.find_element_by_id("modal-bulk-delete-ad-sbmt") 116 | btn_confirm_del.click() 117 | 118 | log.info("\tAd deleted") 119 | fake_wait(randint(2000, 3000)) 120 | webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() 121 | return True 122 | except NoSuchElementException: 123 | log.info("\tDelete button not found") 124 | else: 125 | log.info("\tAd does not exist (anymore)") 126 | 127 | ad.pop("id", None) 128 | return False 129 | 130 | 131 | # From: https://stackoverflow.com/questions/983354/how-do-i-make-python-to-wait-for-a-pressed-key 132 | def wait_key(): 133 | """ Wait for a key press on the console and return it. """ 134 | result = None 135 | if os.name == 'nt': 136 | result = input("Press Enter to continue...") 137 | else: 138 | import termios 139 | fd = sys.stdin.fileno() 140 | 141 | oldterm = termios.tcgetattr(fd) 142 | newattr = termios.tcgetattr(fd) 143 | newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO 144 | termios.tcsetattr(fd, termios.TCSANOW, newattr) 145 | 146 | try: 147 | result = sys.stdin.read(1) 148 | except IOError: 149 | pass 150 | finally: 151 | termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) 152 | 153 | return result 154 | 155 | 156 | def post_ad_has_captcha(driver): 157 | has_captcha = False 158 | 159 | try: 160 | captcha_field = driver.find_element_by_xpath('//*[@id="postAd-recaptcha"]') 161 | if captcha_field: 162 | has_captcha = True 163 | except NoSuchElementException: 164 | pass 165 | 166 | log.info(f"Captcha: {has_captcha}") 167 | 168 | return has_captcha 169 | 170 | 171 | def post_ad_is_allowed(driver): 172 | is_allowed = True 173 | 174 | # Try checking for the monthly limit per account first. 175 | try: 176 | shopping_cart = driver.find_elements_by_xpath('/html/body/div[1]/form/fieldset[6]/div[1]/header') 177 | if shopping_cart: 178 | log.info("\t*** Monthly limit of free ads per account reached! Skipping ... ***") 179 | is_allowed = False 180 | except: 181 | pass 182 | 183 | log.info(f"Ad posting allowed: {is_allowed}") 184 | 185 | return is_allowed 186 | 187 | 188 | def post_ad(driver, ad, interactive): 189 | log.info("\tPublishing ad ...") 190 | 191 | if config['glob_phone_number'] is None: 192 | config['glob_phone_number'] = '' 193 | 194 | if ad["price_type"] not in ['FIXED', 'NEGOTIABLE', 'GIVE_AWAY']: 195 | ad["price_type"] = 'NEGOTIABLE' 196 | 197 | # Navigate to page 198 | driver.get('https://www.ebay-kleinanzeigen.de/p-anzeige-aufgeben.html') 199 | fake_wait(randint(2000, 3500)) 200 | 201 | category_selected = False 202 | try: 203 | driver.find_element_by_id('pstad-lnk-chngeCtgry') 204 | log.info("Using new layout") 205 | except: 206 | log.info("Using old layout") 207 | # legacy handling for old page layout where you have to first select the category (currently old and new layout are served randomly) 208 | driver.get(ad["caturl"].replace('p-kategorie-aendern', 'p-anzeige-aufgeben')) 209 | fake_wait(300) 210 | driver.find_element_by_css_selector("#postad-step1-sbmt button").click() 211 | fake_wait(300) 212 | category_selected = True 213 | 214 | # Check if posting an ad is allowed / possible 215 | fRc = post_ad_is_allowed(driver) 216 | if fRc is False: 217 | return fRc 218 | 219 | # Fill form 220 | if "type" in ad and ad["type"] == "WANTED": 221 | driver.find_element_by_id('adType2').click() 222 | title_input = driver.find_element_by_id('postad-title') 223 | title_input.click() 224 | title_input.send_keys(ad["title"]) 225 | driver.find_element_by_id('pstad-descrptn').click() # click description textarea to lose focus from title field which will trigger category auto detection 226 | if not category_selected: 227 | # wait for category auto detection 228 | try: 229 | WebDriverWait(driver, 3).until(lambda driver: driver.find_element_by_id('postad-category-path').text.strip() != '') 230 | category_selected = True 231 | except: 232 | pass 233 | # Change category if present in config (otherwise keep auto detected category from eBay Kleinanzeigen) 234 | cat_override = ad["caturl"] 235 | if cat_override: 236 | cat_override = cat_override.replace('p-anzeige-aufgeben', 'p-kategorie-aendern') # replace old links for backwards compatibility 237 | driver.find_element_by_id('pstad-lnk-chngeCtgry').click() 238 | WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.ID, 'postad-step1-sbmt'))) 239 | driver.get(cat_override) 240 | fake_wait() 241 | driver.find_element_by_id('postad-step1-sbmt').submit() 242 | fake_wait() 243 | category_selected = True 244 | if not category_selected: 245 | raise Exception('No category configured for this ad and auto detection failed, cannot publish') 246 | 247 | # add additional category fields 248 | additional_category_options = ad.get("additional_category_options", {}) 249 | for element_id, value in additional_category_options.items(): 250 | try: 251 | select_element = driver.find_element_by_css_selector( 252 | 'select[id$="{}"]'.format(element_id) 253 | ) 254 | Select(select_element).select_by_visible_text(value) 255 | except NoSuchElementException: 256 | try: 257 | driver.find_element_by_xpath("//input[@id='%s']" % element_id).send_keys(value) 258 | except NoSuchElementException: 259 | pass 260 | 261 | 262 | text_area = driver.find_element_by_id("pstad-descrptn") 263 | ad_suffix = config.get("glob_ad_suffix", "") 264 | ad_prefix = config.get("glob_ad_prefix", "") 265 | 266 | if ad.get("description_file", None) is not None: 267 | description_file = ad.get("description_file") 268 | with open(description_file, "r", encoding="utf-8") as f: 269 | description_lines = f.readlines() 270 | else: 271 | desc = ad.get("desc") 272 | description_lines = desc.split("\\n") 273 | 274 | description_lines = [x.strip("\\n") for x in description_lines] 275 | description_lines.append(ad_suffix) 276 | description_lines.insert(0, ad_prefix) 277 | 278 | for p in description_lines: 279 | text_area.send_keys(p) 280 | 281 | fake_wait() 282 | 283 | if (ad['shipping_type']) != 'NONE': 284 | try: 285 | select_element = driver.find_element_by_css_selector('select[id$=".versand_s"]') 286 | shipment_select = Select(select_element) 287 | log.debug("\t shipping select found with id: %s" % select_element.get_attribute('id')) 288 | if (ad['shipping_type']) == 'PICKUP': 289 | shipment_select.select_by_visible_text("Nur Abholung") 290 | if (ad['shipping_type']) == 'SHIPPING': 291 | shipment_select.select_by_visible_text("Versand möglich") 292 | fake_wait() 293 | except NoSuchElementException: 294 | pass 295 | 296 | text_area = driver.find_element_by_id('pstad-price') 297 | if ad["price_type"] != 'GIVE_AWAY': 298 | text_area.send_keys(ad["price"]) 299 | price = driver.find_element_by_xpath("//input[@name='priceType' and @value='%s']" % ad["price_type"]) 300 | price.click() 301 | fake_wait() 302 | 303 | text_area = driver.find_element_by_id('pstad-zip') 304 | text_area.clear() 305 | if ad.get("zip", None) is not None: 306 | text_area.send_keys(ad["zip"]) 307 | else: 308 | text_area.send_keys(config["glob_zip"]) 309 | fake_wait() 310 | 311 | if config["glob_phone_number"]: 312 | text_area = driver.find_element_by_id('postad-phonenumber') 313 | text_area.clear() 314 | text_area.send_keys(config["glob_phone_number"]) 315 | fake_wait() 316 | 317 | text_area = driver.find_element_by_id('postad-contactname') 318 | text_area.clear() 319 | text_area.send_keys(config["glob_contact_name"]) 320 | fake_wait() 321 | 322 | if config["glob_street"]: 323 | text_area = driver.find_element_by_id('pstad-street') 324 | text_area.clear() 325 | text_area.send_keys(config["glob_street"]) 326 | fake_wait() 327 | 328 | # Upload images from photofiles 329 | if "photofiles" in ad: 330 | try: 331 | fileup = driver.find_element_by_xpath("//input[@type='file']") 332 | for path in ad["photofiles"]: 333 | path_abs = config["glob_photo_path"] + path 334 | uploaded_count = len(driver.find_elements_by_class_name("imagebox-new-thumbnail")) 335 | log.debug("\tUploading image: %s" % path_abs) 336 | fileup.send_keys(os.path.abspath(path_abs)) 337 | total_upload_time = 0 338 | while uploaded_count == len(driver.find_elements_by_class_name("imagebox-new-thumbnail")) and \ 339 | total_upload_time < 30: 340 | fake_wait(500) 341 | total_upload_time += 0.5 342 | 343 | if uploaded_count == len(driver.find_elements_by_class_name("imagebox-new-thumbnail")): 344 | log.warning("\tCould not upload image: %s within %s seconds" % (path_abs, total_upload_time)) 345 | else: 346 | log.debug("\tUploaded file in %s seconds" % total_upload_time) 347 | except NoSuchElementException: 348 | pass 349 | 350 | # Upload images from directory 351 | if "photo_dir" in ad: 352 | try: 353 | fileup = driver.find_element_by_xpath("//input[@type='file']") 354 | path = ad["photo_dir"] 355 | path_abs = os.path.join(config["glob_photo_path"], path) 356 | if not path_abs.endswith("/"): 357 | path_abs += "/" 358 | for filename in sorted(os.listdir(path_abs)): 359 | if not filename.lower().endswith((".jpg", ".jpeg", ".png", ".gif")): 360 | continue 361 | file_path_abs = path_abs + filename 362 | uploaded_count = len(driver.find_elements_by_class_name("imagebox-new-thumbnail")) 363 | log.debug("\tUploading image: %s" % file_path_abs) 364 | fileup.send_keys(os.path.abspath(file_path_abs)) 365 | total_upload_time = 0 366 | while uploaded_count == len(driver.find_elements_by_class_name("imagebox-new-thumbnail")) and \ 367 | total_upload_time < 60: 368 | fake_wait(1000) 369 | total_upload_time += 1 370 | 371 | if uploaded_count == len(driver.find_elements_by_class_name("imagebox-new-thumbnail")): 372 | log.warning("\tCould not upload image: %s within %s seconds" % (file_path_abs, total_upload_time)) 373 | else: 374 | log.debug("\tUploaded file in %s seconds" % total_upload_time) 375 | except NoSuchElementException as e: 376 | log.error(e) 377 | 378 | fake_wait() 379 | 380 | submit_button = driver.find_element_by_id('pstad-frmprview') 381 | if submit_button: 382 | submit_button.click() 383 | 384 | fake_wait() 385 | 386 | has_captcha = post_ad_has_captcha(driver) 387 | if has_captcha: 388 | if interactive: 389 | log.info("\t*** Manual captcha input needed! ***") 390 | log.info("\tFill out captcha and submit, after that press Enter here to continue ...") 391 | wait_key() 392 | else: 393 | log.info("\tCaptcha input needed, but running in non-interactive mode! Skipping ...") 394 | fRc = False 395 | 396 | if fRc: 397 | try: 398 | submit_button = driver.find_element_by_id('prview-btn-post') 399 | if submit_button: 400 | submit_button.click() 401 | except NoSuchElementException: 402 | pass 403 | 404 | try: 405 | parsed_q = urllib.parse.parse_qs(urllib.parse.urlparse(driver.current_url).query) 406 | add_id = parsed_q.get('adId', None)[0] 407 | log.info(f"\tPosted as: {driver.current_url}") 408 | if "id" not in ad: 409 | log.info(f"\tNew ad ID: {add_id}") 410 | ad["date_published"] = datetime.utcnow().isoformat() 411 | 412 | ad["id"] = add_id 413 | ad["date_updated"] = datetime.utcnow().isoformat() 414 | except: 415 | pass 416 | 417 | if fRc is False: 418 | log.info("\tError publishing ad") 419 | 420 | return fRc 421 | 422 | 423 | def session_create(config): 424 | log.info("Creating session") 425 | 426 | options = webdriver.ChromeOptions() 427 | 428 | if config.get('headless', False) is True: 429 | log.info("Headless mode") 430 | options.add_argument("--headless") 431 | 432 | if os.path.isfile("./chrome-win/chrome.exe"): 433 | log.info("Found ./chrome-win/chrome.exe") 434 | options.binary_location = "./chrome-win/chrome.exe" 435 | 436 | driver = webdriver.Chrome(options=options) 437 | 438 | stealth(driver, 439 | languages=["en-US", "en"], 440 | vendor="Google Inc.", 441 | platform="Win32", 442 | webgl_vendor="Intel Inc.", 443 | renderer="Intel Iris OpenGL Engine", 444 | fix_hairline=True, 445 | ) 446 | log.info("New session is: %s %s" % (driver.session_id, driver.command_executor._url)) 447 | 448 | return driver 449 | 450 | 451 | def signal_handler(sig, frame): 452 | print('Exiting script') 453 | sys.exit(0) 454 | 455 | 456 | if __name__ == '__main__': 457 | 458 | signal.signal(signal.SIGINT, signal_handler) 459 | 460 | try: 461 | aOpts, aArgs = getopt.gnu_getopt(sys.argv[1:], "ph", ["profile=", "help"]) 462 | except getopt.error as msg: 463 | print(msg) 464 | print("For help use --help") 465 | sys.exit(2) 466 | 467 | sProfile = "" 468 | 469 | for o, a in aOpts: 470 | if o in "--profile": 471 | sProfile = a 472 | 473 | if not sProfile: 474 | print("No profile specified") 475 | sys.exit(2) 476 | 477 | log.info('Script started') 478 | log.info("Using profile: %s" % sProfile) 479 | 480 | config = {} 481 | 482 | profile_read(sProfile, config) 483 | 484 | if config.get("headless") is None: 485 | config["headless"] = False 486 | 487 | updateInterval = config.get("update_interval", 4) 488 | 489 | fForceUpdate = False 490 | fDoLogin = True 491 | 492 | dtNow = datetime.utcnow() 493 | 494 | driver = session_create(config) 495 | profile_write(sProfile, config) 496 | login(config) 497 | fake_wait(randint(1000, 4000)) 498 | for ad in config['ads']: 499 | assert len(ad["title"]) > 9, "eBay restriction: Title must be at least 10 chars long" 500 | 501 | for ad in config["ads"]: 502 | 503 | fNeedsUpdate = False 504 | 505 | log.info("Handling '%s'" % ad["title"]) 506 | 507 | if "date_updated" in ad: 508 | # python < 3.7 do not support datetime.datetime_fromisoformat() 509 | # https://stackoverflow.com/a/60852111/256002 510 | if int(python_version_tuple()[1]) < 7: 511 | from backports.datetime_fromisoformat import MonkeyPatch 512 | MonkeyPatch.patch_fromisoformat() 513 | 514 | dtLastUpdated = datetime.fromisoformat(ad["date_updated"]) 515 | else: 516 | dtLastUpdated = dtNow 517 | dtDiff = dtNow - dtLastUpdated 518 | 519 | if "enabled" in ad and ad["enabled"] == "1": 520 | if "date_published" in ad: 521 | log.info("\tAlready published (%d days ago)" % dtDiff.days) 522 | if dtDiff.days > updateInterval: 523 | fNeedsUpdate = True 524 | else: 525 | log.info("\tNot published yet") 526 | fNeedsUpdate = True 527 | else: 528 | log.info("\tDisabled, skipping") 529 | 530 | if fNeedsUpdate or fForceUpdate: 531 | 532 | # delete ad if it was published already 533 | if "id" in ad or "date_published" in ad: 534 | delete_ad(driver, ad) 535 | 536 | fPosted = post_ad(driver, ad, True) 537 | if not fPosted: 538 | break 539 | 540 | log.info("Waiting for handling next ad ...") 541 | fake_wait(randint(2000, 6000)) 542 | 543 | profile_write(sProfile, config) 544 | 545 | driver.close() 546 | log.info("Script done") 547 | --------------------------------------------------------------------------------