├── .gitignore ├── LICENSE ├── PriceMonitor ├── CONFIG.py ├── __init__.py ├── consumer_jd_crawl.py ├── consumer_mail.py ├── crawler_js.py ├── crawler_selenium.py ├── database │ ├── __init__.py │ ├── model │ │ ├── __init__.py │ │ ├── pm_mail_record.py │ │ ├── pm_monitor_item.py │ │ └── pm_user.py │ └── sql_operator.py ├── mail.py ├── mailbox.txt ├── producer_jd_crawl.py ├── producer_mail.py └── proxy.py ├── README.md ├── docs ├── Email01.png ├── Email02.png ├── Pagedemo.png ├── Pagedemo2.png ├── Pagedemo3.png ├── Pagedemo4.png ├── SetupEmail.md ├── Sqlitedemo.png └── Structure.png └── 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 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | # pricemonitor 104 | PriceMonitor/mailbox.txt 105 | PriceMonitor/db_demo.db 106 | .idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /PriceMonitor/CONFIG.py: -------------------------------------------------------------------------------- 1 | # Monitor 2 | PROXY_CRAWL = 0 # 0: Use local ip 1: Use proxy pool 2: Use zhi ma ip 3 | SELENIUM_THREAD = 1 4 | EMAIL_FIRST_ALERT_WAIT_TIME = 0 # Avoid to send redundant email when items added 5 | DISCOUNT_LIMIT = 0.7 # Set alert mail discount for user item. 6 | 7 | # Mysql config 8 | MYSQL_USER = 'root' 9 | MYSQL_PORT = 3306 10 | MYSQL_CHARSET = 'utf8' 11 | 12 | MYSQL_HOST = 'localhost' 13 | MYSQL_PASSWORD = 'root' 14 | 15 | # RabbitMq 16 | RABBIT_MQ_HOST = 'localhost' -------------------------------------------------------------------------------- /PriceMonitor/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qqxx6661/Price-monitor/ca0b0e6c0054446fb3538c63f597e2562ae97297/PriceMonitor/__init__.py -------------------------------------------------------------------------------- /PriceMonitor/consumer_jd_crawl.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import os 4 | import time 5 | 6 | import pika 7 | 8 | from CONFIG import RABBIT_MQ_HOST, SELENIUM_THREAD 9 | from crawler_selenium import Crawler 10 | from database.sql_operator import SqlOperator 11 | from producer_mail import ProducerMail 12 | 13 | 14 | class ConsumerJdCrawl: 15 | sql_operator = None 16 | executor = None 17 | 18 | def __init__(self): 19 | 20 | # 数据库连接初始化 21 | self.sql_operator = SqlOperator() 22 | # 订阅频道 23 | connection = pika.BlockingConnection(pika.ConnectionParameters(host=RABBIT_MQ_HOST)) 24 | channel = connection.channel() 25 | # 如果确定已经声明了,可以不声明。但是你不知道消费者生产者哪个先运行,所以要声明两次。 26 | channel.queue_declare(queue='jd_crawl') 27 | # prefetch_count 如果消费者中有一条消息没有处理完,就不会继续给这个消费者发送新消息 28 | channel.basic_qos(prefetch_count=SELENIUM_THREAD) 29 | channel.basic_consume('jd_crawl', self.callback) 30 | logging.info('开始监听Queue:jd_crawl') 31 | channel.start_consuming() 32 | 33 | def callback(self, ch, method, properties, body): # 四个参数为标准格式 34 | logging.info("收到消息: %r 序号为:%r" % (body, method.delivery_tag)) 35 | self.thread_run(ch, method, body) 36 | 37 | def thread_run(self, ch, method, body): 38 | logging.info("线程开始处理消息: %r 序号为:%r" % (body, method.delivery_tag)) 39 | # 爬取商品 40 | # crawl_data:{'id': "1532", 'item_id': "4749125"} 41 | try: 42 | crawl_data = json.loads(body) 43 | except BaseException: 44 | logging.info("消息结构不对,丢弃,发送确认序号: %r" % method.delivery_tag) 45 | ch.basic_ack(delivery_tag=method.delivery_tag) 46 | return 47 | item_info, huihui_info = self.jd_crawl(crawl_data) 48 | # 存入数据库 49 | self.sql_operator.update_pm_monitor_item(crawl_data, item_info, huihui_info) 50 | # 确认是否需要邮件发送,若是则发送邮件到消息队列 51 | is_email_needed = self.sql_operator.query_email_alert_needed(crawl_data["id"]) 52 | if is_email_needed: 53 | logging.info("需要发送邮件提醒,pm_monitor_id:[{}]".format(crawl_data["id"])) 54 | # 获取用户信息 55 | user_info = self.sql_operator.query_user_info(crawl_data["id"]) 56 | item_info_all = self.sql_operator.query_pm_monitor_item(crawl_data["id"]) 57 | # 调用发送邮件队列 58 | self.mail_fill(user_info, item_info_all) 59 | # delivery_tag是确认序号 60 | logging.info("消息处理完成,发送确认序号: %r" % method.delivery_tag) 61 | ch.basic_ack(delivery_tag=method.delivery_tag) 62 | 63 | def jd_crawl(self, crawl_data): 64 | """ 65 | 爬取某东商品数据和慧慧最高最低价数据 66 | """ 67 | logging.info("开始爬取:{}".format(crawl_data)) 68 | start = time.time() 69 | item_info, huihui_info = self.crawl(crawl_data) 70 | end = time.time() 71 | logging.info("爬虫执行时间: {}".format(end - start)) 72 | return item_info, huihui_info 73 | 74 | @staticmethod 75 | def mail_fill(user_info, item_info): 76 | """ 77 | 填充邮件内容 78 | """ 79 | logging.info("开始撰写提醒邮件内容") 80 | if not item_info.min_price: 81 | item_info.min_price = '暂无历史最低价格' 82 | item_info.max_price = '暂无历史最高价格' 83 | item_url = 'https://item.jd.com/' + str(item_info.item_id) + '.html' 84 | email_text = '监控更新,增加会员监控功能,未来将努力打造为一站式监控平台,欢迎提需求和建议。\n\n' 85 | if not item_info.last_price: 86 | email_text += '物品:' + item_info.name + ',\n现在价格为:' + str(item_info.price) + \ 87 | '\n您设定的价格为: ' + str(item_info.user_price) + '\n子标题:' + item_info.subtitle + \ 88 | '\n历史最高价参考(不准确参考):' + str(item_info.max_price) + '\n历史最低价参考(不准确参考):' + str(item_info.min_price) + \ 89 | '\n' + item_url + '\n\n\n' 90 | else: 91 | email_text += '物品:' + item_info.name + ',\n上次监控价格为:' + str(item_info.last_price) + \ 92 | ',\n现在价格为:' + str(item_info.price) + '\n您设定的价格为: ' + str(item_info.user_price) + \ 93 | '\n降价幅度为:' + str(round(10 * float(item_info.discount), 2)) + '折,赶紧购买吧!' + \ 94 | '\n子标题:' + item_info.subtitle + '\n历史最高价参考(不准确参考):' + str(item_info.max_price) + \ 95 | '\n历史最低价参考(不准确参考):' + str(item_info.min_price) + '\n' + item_url + '\n\n\n' 96 | email_subject = '【电商价格监控】设定商品降价通知' 97 | 98 | data = dict() 99 | data["msg"] = email_text 100 | data["from"] = '电商价格监控' 101 | data["to"] = '注册用户' 102 | data["subject"] = email_subject 103 | data["address"] = user_info["email"] 104 | data["id"] = item_info.id 105 | ProducerMail.send_mail_message(data) 106 | logging.info("提醒邮件已经发送进队列") 107 | 108 | @staticmethod 109 | def crawl(crawl_data): 110 | retry = 2 111 | item_info = {"name": None, "price": None, "plus_price": None, "subtitle": None} 112 | while retry: 113 | try: 114 | crawler_jd = Crawler() 115 | # dict: {"name", "price", "subtitle", "plus_price"} 116 | item_info = crawler_jd.get_jd_item(str(crawl_data["item_id"])) 117 | crawler_jd.close() 118 | except ConnectionResetError: 119 | retry -= 1 120 | logging.warning('proxy connection reset by peer,delete proxy and retrying: {} left.'.format(retry)) 121 | continue 122 | if not item_info["price"]: 123 | retry -= 1 124 | logging.warning('Cannot get item price,delete proxy and retrying: {} left.'.format(retry)) 125 | continue 126 | else: 127 | break 128 | # 慧慧最低最高价接口已经失效,不再访问 129 | huihui_info = {"max_price": None, "min_price": None} 130 | # crawler_huihui = Crawler() 131 | # # dict: {"max_price", "min_price"} 132 | # huihui_info = crawler_huihui.get_huihui_item(str(crawl_data["item_id"])) 133 | # crawler_huihui.close() 134 | return item_info, huihui_info 135 | 136 | if __name__ == '__main__': 137 | logging.basicConfig(format="%(asctime)s | %(levelname)s | %(filename)s %(lineno)s | %(message)s", 138 | datefmt="%Y-%m-%d %H:%M:%S", 139 | level=logging.INFO) 140 | thread = ConsumerJdCrawl() 141 | -------------------------------------------------------------------------------- /PriceMonitor/consumer_mail.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | 4 | import pika 5 | 6 | from CONFIG import RABBIT_MQ_HOST 7 | from database.sql_operator import SqlOperator 8 | 9 | from PriceMonitor.mail import Mail 10 | 11 | 12 | class ConsumerJdCrawl: 13 | sql_operator = None 14 | 15 | def __init__(self): 16 | 17 | # 数据库连接初始化 18 | self.sql_operator = SqlOperator() 19 | # 订阅频道 20 | connection = pika.BlockingConnection(pika.ConnectionParameters(host=RABBIT_MQ_HOST)) 21 | channel = connection.channel() 22 | # 如果确定已经声明了,可以不声明。但是你不知道消费者生产者哪个先运行,所以要声明两次。 23 | channel.queue_declare(queue='mail') 24 | channel.basic_consume('mail', self.callback) 25 | logging.info('开始监听Queue:mail') 26 | channel.start_consuming() 27 | 28 | def callback(self, ch, method, properties, body): # 四个参数为标准格式 29 | logging.info("收到消息: %r 序号为:%r" % (body, method.delivery_tag)) 30 | self.thread_run(ch, method, body) 31 | 32 | def thread_run(self, ch, method, body): 33 | logging.info("线程开始处理消息: %r 序号为:%r" % (body, method.delivery_tag)) 34 | data = json.loads(body) 35 | # 再次确认是否需要发邮件,防止并发爬虫检查都为0 36 | is_email_needed = self.sql_operator.query_email_alert_needed(data["id"]) 37 | if not is_email_needed: 38 | logging.info("发送邮件前检查is_alert状态为0,不需要重复提醒: %r" % method.delivery_tag) 39 | logging.info("消息不作发送邮件处理,发送确认序号: %r" % method.delivery_tag) 40 | return 41 | logging.info("发送邮件:", data) 42 | send_email = Mail(data["msg"], data["from"], data["to"], data["subject"], data["address"]) 43 | is_sent = send_email.send() 44 | # 将数据库alert改为0 45 | if is_sent: 46 | self.sql_operator.update_alert_info(data["id"], 0) 47 | # delivery_tag是确认序号 48 | logging.info("消息处理完成,发送确认序号: %r" % method.delivery_tag) 49 | ch.basic_ack(delivery_tag=method.delivery_tag) 50 | 51 | 52 | 53 | if __name__ == '__main__': 54 | logging.basicConfig(format="%(asctime)s | %(levelname)s | %(filename)s %(lineno)s | %(message)s", 55 | datefmt="%Y-%m-%d %H:%M:%S", 56 | level=logging.INFO) 57 | thread = ConsumerJdCrawl() 58 | -------------------------------------------------------------------------------- /PriceMonitor/crawler_js.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | import requests 4 | import json 5 | from lxml import etree 6 | import logging 7 | 8 | 9 | class Crawler(object): 10 | 11 | @staticmethod 12 | def get_info_huihui(item_id, header, proxy=None): 13 | url = 'https://zhushou.huihui.cn/productSense?phu=https://item.jd.com/' + item_id + '.html' 14 | logging.debug('Ready to crawl huihui price URL:%s', url) 15 | try: 16 | if proxy: # Using proxy 17 | proxies = proxy 18 | r = requests.get(url, headers=header, proxies=proxies, timeout=5) 19 | else: # Not using proxy 20 | logging.info('Not using proxy to crawl huihui') 21 | r = requests.get(url, headers=header, timeout=5) 22 | max_price = r.json()['max'] 23 | min_price = r.json()['min'] 24 | logging.info('max and min price: %s, %s', max_price, min_price) 25 | return max_price, min_price 26 | 27 | except requests.exceptions.ProxyError as e: 28 | logging.info('Proxy error: %s', e) 29 | return False 30 | except requests.exceptions.ConnectionError as e: 31 | logging.info('Https error: %s', e) 32 | return False 33 | except requests.exceptions.ReadTimeout as e: 34 | logging.info('Timeout error: %s', e) 35 | return False 36 | except requests.exceptions.ChunkedEncodingError as e: 37 | logging.info('ChunkedEncodingError error: %s', e) 38 | return False 39 | 40 | @staticmethod 41 | def get_subtitle_jd(item_id, header, proxy=None): 42 | url = 'https://cd.jd.com/promotion/v2?callback=jQuery6525446&skuId=' + item_id + \ 43 | '5181380&area=1_72_2799_0&shopId=1000000904&venderId=1000000904&cat=9987%2C653%2C655' 44 | logging.debug('Ready to crawl jd subtitle URL:%s', url) 45 | try: 46 | if proxy: # Using proxy 47 | proxies = proxy 48 | r = requests.get(url, headers=header, proxies=proxies, timeout=5) 49 | else: # Not using proxy 50 | logging.info('Not using proxy to crawl subtitle') 51 | r = requests.get(url, headers=header, timeout=5) 52 | subtitle = r.text 53 | try: 54 | subtitle = subtitle[14:-1] 55 | print(subtitle) 56 | subtitle_js = json.loads(str(subtitle)) 57 | except json.decoder.JSONDecodeError as e: 58 | logging.info('Captcha error: %s', e) 59 | return False 60 | logging.info('subtitle: %s', subtitle) 61 | return subtitle_js['ads'][0]['ad'] 62 | except requests.exceptions.ProxyError as e: 63 | logging.info('Proxy error: %s', e) 64 | return False 65 | except requests.exceptions.ConnectionError as e: 66 | logging.info('Https error: %s', e) 67 | return False 68 | except requests.exceptions.ReadTimeout as e: 69 | logging.info('Timeout error: %s', e) 70 | return False 71 | except requests.exceptions.ChunkedEncodingError as e: 72 | logging.info('ChunkedEncodingError error: %s', e) 73 | return False 74 | 75 | @staticmethod 76 | def get_price_jd(item_id, header, proxy=None): 77 | url = 'https://p.3.cn/prices/mgets?callback=&skuIds=J_' + item_id 78 | logging.debug('Ready to crawl JD price URL:%s', url) 79 | try: 80 | if proxy: # Using proxy 81 | proxies = proxy 82 | r = requests.get(url, headers=header, proxies=proxies, timeout=5) 83 | else: # Not using proxy 84 | logging.info('Not using proxy to crawl price') 85 | r = requests.get(url, headers=header, timeout=5) 86 | price = r.text 87 | # can not use status code because wrong id also get 200 88 | if price == 'skuids input error\n': # Avoid invalid item id 89 | js_fake = '-1' 90 | return js_fake 91 | try: 92 | price = price[2:-4] 93 | price_js = json.loads(str(price)) 94 | except json.decoder.JSONDecodeError as e: 95 | logging.info('Captcha error: %s', e) 96 | return False 97 | logging.info('Item: %s ,price JS: %s', item_id, price_js) 98 | return price_js['p'] 99 | except requests.exceptions.ProxyError as e: 100 | logging.info('Proxy error: %s', e) 101 | return False 102 | except requests.exceptions.ConnectionError as e: 103 | logging.info('Https error: %s', e) 104 | return False 105 | except requests.exceptions.ReadTimeout as e: 106 | logging.info('Timeout error: %s', e) 107 | return False 108 | except requests.exceptions.ChunkedEncodingError as e: 109 | logging.info('ChunkedEncodingError error: %s', e) 110 | return False 111 | 112 | @staticmethod 113 | def get_name_jd(item_id, header, proxy=None): 114 | url = 'https://item.jd.com/' + item_id + '.html' 115 | logging.debug('Ready to crawl JD name URL:%s', url) 116 | try: 117 | if proxy: # Using proxy 118 | logging.info('Using proxy to crawl: %s', proxy) 119 | r = requests.get(url, headers=header, proxies=proxy, timeout=6) 120 | else: # Not using proxy 121 | logging.info('Not using proxy to crawl name') 122 | r = requests.get(url, headers=header, timeout=6) 123 | selector = etree.HTML(r.text) 124 | name = selector.xpath("//*[@class='sku-name']/text()") # list 125 | try: # normal 126 | name_true = name[0].strip() 127 | if not len(name_true): # jd chaoshi 128 | logging.info('Change method to catch name: jd chaoshi') 129 | name_true = name[1].strip() 130 | except IndexError as e: 131 | logging.info(e, name) 132 | logging.info('Change method to catch name: jd jingxuan') 133 | try: # jd jingxuan 134 | name = selector.xpath("//*[@id='name']/h1/text()") 135 | name_true = name[0].strip() 136 | except IndexError as e: 137 | logging.warning(e, name) 138 | logging.warning('Catch name error') 139 | name_true = '本轮抓取该商品名称失败,请等待重试' 140 | return name_true 141 | logging.info('Item: %s', name_true) 142 | return name_true 143 | except requests.exceptions.ProxyError as e: 144 | logging.info('Proxy error: %s', e) 145 | return '' # as False 146 | except requests.exceptions.ConnectionError as e: 147 | logging.info('Https error: %s', e) 148 | return '' # as False 149 | except requests.exceptions.ReadTimeout as e: 150 | logging.info('Timeout error: %s', e) 151 | return '' # as False 152 | except requests.exceptions.ChunkedEncodingError as e: 153 | logging.info('ChunkedEncodingError error: %s', e) 154 | return '' # as False 155 | 156 | 157 | if __name__ == '__main__': 158 | logging.basicConfig(level=logging.INFO) 159 | c = Crawler() 160 | logging.debug(c.get_price_jd('2777811', {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' 161 | 'AppleWebKit/536.6 (KHTML, like Gecko) ' 162 | 'Chrome/20.0.1092.0 Safari/536.6'})) 163 | logging.debug(c.get_name_jd('2777811', {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' 164 | 'AppleWebKit/536.6 (KHTML, like Gecko) ' 165 | 'Chrome/20.0.1092.0 Safari/536.6'})) 166 | logging.debug(c.get_subtitle_jd('5181380', {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' 167 | 'AppleWebKit/536.6 (KHTML, like Gecko) ' 168 | 'Chrome/20.0.1092.0 Safari/536.6'})) 169 | logging.debug(c.get_info_huihui('2777811', {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) ' 170 | 'AppleWebKit/536.6 (KHTML, like Gecko) ' 171 | 'Chrome/20.0.1092.0 Safari/536.6'})) 172 | -------------------------------------------------------------------------------- /PriceMonitor/crawler_selenium.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | import json 4 | import logging 5 | import re 6 | import time 7 | from json import decoder 8 | from selenium import webdriver 9 | from selenium.common.exceptions import NoSuchElementException, TimeoutException, StaleElementReferenceException 10 | from selenium.webdriver import DesiredCapabilities 11 | from selenium.webdriver.chrome.options import Options 12 | 13 | class Crawler(object): 14 | 15 | def __init__(self, proxy=None): 16 | chrome_options = Options() 17 | chrome_options.add_argument('--headless') 18 | chrome_options.add_argument('--disable-gpu') 19 | chrome_options.add_argument('--no-sandbox') 20 | chrome_options.add_argument('--disable-dev-shm-usage') 21 | chrome_options.add_argument('--ignore-certificate-errors') 22 | chrome_options.add_argument('--ignore-ssl-errors') 23 | prefs = {"profile.managed_default_content_settings.images": 2} 24 | chrome_options.add_experimental_option("prefs", prefs) 25 | if proxy: 26 | proxy_address = proxy['https'] 27 | chrome_options.add_argument('--proxy-server=%s' % proxy_address) 28 | logging.info('Chrome using proxy: %s', proxy['https']) 29 | # 设置等待策略为不等待完全加载 30 | caps = DesiredCapabilities().CHROME 31 | caps["pageLoadStrategy"] = "none" 32 | self.chrome = webdriver.Chrome(chrome_options=chrome_options, desired_capabilities=caps) 33 | # jd sometimes load google pic takes much time 34 | self.chrome.set_page_load_timeout(30) 35 | # set timeout for script 36 | self.chrome.set_script_timeout(30) 37 | 38 | def close(self): 39 | self.chrome.quit() 40 | 41 | def get_jd_item(self, item_id): 42 | item_info_dict = {"name": None, "price": None, "plus_price": None, "subtitle": None} 43 | url = 'https://item.jd.com/' + item_id + '.html' 44 | try: 45 | self.chrome.get(url) 46 | logging.info('Crawl: {}'.format(url)) 47 | # 共60秒 48 | retry = 30 49 | while retry: 50 | try: 51 | element = self.chrome.find_element_by_xpath("//*[@class='p-price']/span[2]").text 52 | if element: 53 | logging.info("爬取价格数据") 54 | logging.info('Found price element: {}'.format(element)) 55 | break 56 | else: 57 | logging.info("价格元素出现,价格未出现重试2秒") 58 | time.sleep(2) 59 | retry -= 1 60 | except NoSuchElementException: 61 | logging.info("价格元素未出现") 62 | time.sleep(2) 63 | retry -= 1 64 | except TimeoutException as e: 65 | logging.warning('Crawl failure: {}'.format(e.msg)) 66 | return item_info_dict 67 | 68 | # 提取商品名称 69 | try: 70 | name = self.chrome.find_element_by_xpath("//*[@class='sku-name']").text 71 | item_info_dict['name'] = name 72 | except AttributeError as e: 73 | logging.warning('Crawl name failure: {}'.format(e)) 74 | except NoSuchElementException: 75 | try: 76 | # 加油卡(如200117841739)需要改为提取name 77 | name = self.chrome.find_element_by_xpath("//*[@class='name']").text 78 | item_info_dict['name'] = name 79 | except NoSuchElementException as e: 80 | logging.warning('Crawl name failure: {}'.format(e.msg)) 81 | 82 | # 提取商品PLUS价格 83 | try: # 海外购(32533649560)页面无p-price-plus元素,直接保留为None 84 | plus_price = self.chrome.find_element_by_xpath("//*[@class='p-price-plus']").text 85 | if plus_price: 86 | plus_price_xpath = re.findall(r'-?\d+\.?\d*e?-?\d*?', plus_price) 87 | item_info_dict['plus_price'] = plus_price_xpath[0] # 提取浮点数 88 | except AttributeError as e: 89 | logging.warning('Crawl plus_price failure: {}'.format(e)) 90 | except NoSuchElementException as e: 91 | logging.warning('Crawl plus_price failure: {}'.format(e.msg)) 92 | 93 | # 提取商品副标题 94 | try: 95 | subtitle = self.chrome.find_element_by_xpath("//*[@id='p-ad']").text 96 | item_info_dict['subtitle'] = subtitle 97 | except AttributeError as e: 98 | logging.warning('Crawl subtitle failure: {}'.format(e)) 99 | except NoSuchElementException: 100 | try: 101 | # 加油卡200117841739需要改为提取name-s 102 | subtitle = self.chrome.find_element_by_xpath("//*[@class='name-s']").text 103 | item_info_dict['subtitle'] = subtitle 104 | except NoSuchElementException as e: 105 | logging.warning('Crawl subtitle failure: {}'.format(e.msg)) 106 | 107 | # 提取商品价格 108 | try: 109 | price = self.chrome.find_element_by_xpath("//*[@class='p-price']").text 110 | if price: 111 | price_xpath = re.findall(r'-?\d+\.?\d*e?-?\d*?', price) 112 | if price_xpath: # 若能提取到值 113 | item_info_dict['price'] = price_xpath[0] # 提取浮点数 114 | except AttributeError as e: 115 | logging.warning('Crawl price failure: {}'.format(e.msg)) 116 | except NoSuchElementException as e: 117 | logging.warning('Crawl price failure: {}'.format(e.msg)) 118 | return item_info_dict 119 | 120 | logging.info('Crawl SUCCESS: {}'.format(item_info_dict)) 121 | return item_info_dict 122 | 123 | def get_huihui_item(self, item_id): 124 | huihui_info_dict = {"max_price": None, "min_price": None} 125 | url = 'https://zhushou.huihui.cn/productSense?phu=https://item.jd.com/' + item_id + '.html' 126 | try: 127 | self.chrome.get(url) 128 | # 共30秒 129 | retry = 15 130 | while retry: 131 | try: 132 | element = self.chrome.find_element_by_tag_name('body').text 133 | if element: 134 | logging.info('Found body element: {}'.format(element)) 135 | break 136 | else: 137 | logging.info("huihui body元素出现,内容未出现重试2秒") 138 | time.sleep(2) 139 | retry -= 1 140 | except NoSuchElementException: 141 | time.sleep(2) 142 | retry -= 1 143 | except StaleElementReferenceException: 144 | time.sleep(2) 145 | retry -= 1 146 | url_text = self.chrome.find_element_by_tag_name('body').text 147 | info = json.loads(url_text) 148 | huihui_info_dict = {"max_price": info['max'], "min_price": info['min']} 149 | logging.info(huihui_info_dict) 150 | except decoder.JSONDecodeError as e: 151 | logging.warning('Crawl failure: {}'.format(e.msg)) 152 | except NoSuchElementException as e: 153 | logging.warning('Crawl failure: {}'.format(e.msg)) 154 | except TimeoutException as e: 155 | logging.warning('Crawl failure: {}'.format(e.msg)) 156 | return huihui_info_dict 157 | 158 | 159 | if __name__ == '__main__': 160 | logging.basicConfig(format="%(asctime)s | %(levelname)s | %(filename)s %(lineno)s | %(message)s", 161 | datefmt="%Y-%m-%d %H:%M:%S", 162 | level=logging.INFO) 163 | start = time.time() 164 | 165 | c = Crawler() 166 | # c = Crawler({'http': '125.105.32.168:7305', 'https': '171.211.32.79:2456'}) 167 | 168 | # logging.debug(c.get_jd_item('10761604532')) 169 | logging.debug(c.get_jd_item('6287165')) 170 | logging.debug(c.get_huihui_item('30445355110')) 171 | 172 | c.close() 173 | 174 | end = time.time() 175 | print("执行时间:", end - start) 176 | -------------------------------------------------------------------------------- /PriceMonitor/database/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qqxx6661/Price-monitor/ca0b0e6c0054446fb3538c63f597e2562ae97297/PriceMonitor/database/__init__.py -------------------------------------------------------------------------------- /PriceMonitor/database/model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qqxx6661/Price-monitor/ca0b0e6c0054446fb3538c63f597e2562ae97297/PriceMonitor/database/model/__init__.py -------------------------------------------------------------------------------- /PriceMonitor/database/model/pm_mail_record.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from sqlalchemy import Column, DateTime, String, text, create_engine 3 | from sqlalchemy.dialects.mysql import INTEGER, TINYINT 4 | from sqlalchemy.ext.declarative import declarative_base 5 | 6 | Base = declarative_base() 7 | metadata = Base.metadata 8 | 9 | 10 | class PmMailRecord(Base): 11 | __tablename__ = 'pm_mail_record' 12 | 13 | id = Column(INTEGER(20), primary_key=True, comment='主键id') 14 | address = Column(String(64), nullable=False, comment='邮箱地址') 15 | _from = Column('from', String(64), nullable=False, comment='发件人昵称') 16 | to = Column(String(64), nullable=False, comment='收件人昵称') 17 | subject = Column(String(64), nullable=False, comment='主题') 18 | content = Column(String(4096), nullable=False, comment='内容') 19 | is_sent = Column(TINYINT(3), nullable=False, comment='1-发送成功, 0-发送失败') 20 | gmt_create = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP"), comment='创建时间') 21 | gmt_modified = Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"), comment='更新时间') 22 | 23 | if __name__ == '__main__': 24 | engine = create_engine('mysql+pymysql://root:root@localhost/pricemonitor?charset=utf8', echo=True) 25 | Base.metadata.create_all(engine) 26 | -------------------------------------------------------------------------------- /PriceMonitor/database/model/pm_monitor_item.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from sqlalchemy import Column, DateTime, String, create_engine 3 | from sqlalchemy.dialects.mysql import BIGINT, INTEGER, TINYINT 4 | from sqlalchemy.ext.declarative import declarative_base 5 | 6 | Base = declarative_base() 7 | metadata = Base.metadata 8 | 9 | 10 | class PmMonitorItem(Base): 11 | __tablename__ = 'pm_monitor_item' 12 | 13 | id = Column(INTEGER(11), primary_key=True) 14 | user_id = Column(INTEGER(11), nullable=False) 15 | user_price = Column(String(10), nullable=False) 16 | item_id = Column(BIGINT(20), nullable=False) 17 | category_id = Column(BIGINT(20)) 18 | name = Column(String(256)) 19 | subtitle = Column(String(512)) 20 | price = Column(String(32)) 21 | plus_price = Column(String(32)) 22 | max_price = Column(String(32)) 23 | min_price = Column(String(32)) 24 | discount = Column(String(32)) 25 | last_price = Column(String(32)) 26 | note = Column(String(128), comment='备注(保留字段)') 27 | sale = Column(String(128)) 28 | label = Column(String(128)) 29 | store_name = Column(String(128)) 30 | is_ziying = Column(TINYINT(1), comment='是否自营') 31 | is_alert = Column(TINYINT(1), nullable=False, comment='是否已经提醒') 32 | gmt_create = Column(DateTime) 33 | gmt_modified = Column(DateTime) 34 | 35 | if __name__ == '__main__': 36 | engine = create_engine('mysql+pymysql://root:root@localhost/pricemonitor?charset=utf8', echo=True) 37 | Base.metadata.create_all(engine) -------------------------------------------------------------------------------- /PriceMonitor/database/model/pm_user.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from sqlalchemy import Column, DateTime, String, text, create_engine 3 | from sqlalchemy.dialects.mysql import INTEGER, TINYINT 4 | from sqlalchemy.ext.declarative import declarative_base 5 | 6 | Base = declarative_base() 7 | metadata = Base.metadata 8 | 9 | 10 | class PmUser(Base): 11 | __tablename__ = 'pm_user' 12 | 13 | id = Column(INTEGER(11), primary_key=True) 14 | name = Column(String(40)) 15 | email = Column(String(40), nullable=False, unique=True) 16 | phone = Column(String(20)) 17 | password = Column(String(255), nullable=False) 18 | is_active = Column(TINYINT(1), nullable=False, comment='是否活跃账号') 19 | is_superuser = Column(TINYINT(1), nullable=False, comment='是否管理员') 20 | is_olduser = Column(TINYINT(1), server_default=text("'0'")) 21 | gmt_create = Column(DateTime) 22 | gmt_modified = Column(DateTime) 23 | 24 | if __name__ == '__main__': 25 | engine = create_engine('mysql+pymysql://root:root@localhost/pricemonitor?charset=utf8', echo=True) 26 | Base.metadata.create_all(engine) -------------------------------------------------------------------------------- /PriceMonitor/database/sql_operator.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import logging 3 | 4 | from sqlalchemy import create_engine 5 | from sqlalchemy.orm import sessionmaker 6 | 7 | from CONFIG import MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_PORT, MYSQL_CHARSET, EMAIL_FIRST_ALERT_WAIT_TIME, \ 8 | DISCOUNT_LIMIT 9 | from database.model.pm_mail_record import PmMailRecord 10 | from database.model.pm_monitor_item import PmMonitorItem 11 | from database.model.pm_user import PmUser 12 | 13 | 14 | class SqlOperator: 15 | DBSession = None 16 | 17 | def __init__(self): 18 | """ 19 | 初始化数据库连接 20 | """ 21 | conn = "mysql+pymysql://{}:{}@{}:{}/pricemonitor?charset={}".format(MYSQL_USER, MYSQL_PASSWORD, MYSQL_HOST, 22 | MYSQL_PORT, MYSQL_CHARSET) 23 | logging.info("初始化数据库连接:{}".format(conn)) 24 | engine = create_engine(conn) 25 | self.DBSession = sessionmaker(bind=engine) 26 | 27 | def update_pm_monitor_item(self, crawl_info, item_info, huihui_info): 28 | """ 29 | 更新商品数据 30 | """ 31 | logging.info("更新某东商品数据开始:{} {}".format(crawl_info, item_info)) 32 | if not item_info["price"]: 33 | logging.info("爬虫获取价格数据为空,不更新数据库") 34 | return 35 | session = self.DBSession() 36 | record = session.query(PmMonitorItem).filter(PmMonitorItem.id == crawl_info["id"]).one() 37 | # 已有价格数据,若价格变化,写入上次价格和折扣 38 | if record.price and float(record.price) != float(item_info["price"]): 39 | last_price = record.price 40 | discount = round(float(item_info["price"]) / float(last_price), 2) 41 | logging.info("商品价格变动,现价:{},原价:{},写入折扣:{}".format(item_info["price"], record.price, discount)) 42 | record.discount = discount 43 | record.last_price = last_price 44 | record.name = item_info["name"] 45 | record.subtitle = item_info["subtitle"] 46 | record.price = item_info["price"] 47 | record.plus_price = item_info["plus_price"] 48 | record.max_price = huihui_info["max_price"] 49 | record.min_price = huihui_info["min_price"] 50 | record.gmt_modified = datetime.datetime.now() 51 | session.commit() 52 | session.close() 53 | logging.info("更新某东商品数据完成") 54 | 55 | def query_email_alert_needed(self, monitor_item_id): 56 | """ 57 | 查询是否需要邮件提醒:创建时间15分钟内不提醒 58 | """ 59 | logging.info("查询表记录Id:{} 是否需要邮件提醒".format(monitor_item_id)) 60 | 61 | # 取数据库 62 | session = self.DBSession() 63 | record = session.query(PmMonitorItem).filter(PmMonitorItem.id == monitor_item_id).one() 64 | user_price = record.user_price 65 | price = record.price 66 | plus_price = record.plus_price 67 | is_alert = record.is_alert 68 | gmt_create = record.gmt_create 69 | discount = record.discount 70 | # logging.info("user_price:{}".format(user_price)) 71 | # logging.info("item_price:{}".format(price)) 72 | # logging.info("plus_price:{}".format(plus_price)) 73 | # logging.info("is_alert:{}".format(is_alert)) 74 | # logging.info("gmt_create:{}".format(gmt_create)) 75 | session.close() 76 | 77 | # 判断逻辑 78 | if not price: 79 | logging.info("爬虫获取价格数据为空,不提醒") 80 | return False 81 | lowest_price = user_price 82 | if plus_price: 83 | lowest_price = plus_price if (plus_price <= user_price) else user_price 84 | time_delta = datetime.datetime.now() - gmt_create 85 | # 商品价格低于设定价格 86 | if float(lowest_price) >= float(price) and is_alert == 1 and time_delta.total_seconds() > EMAIL_FIRST_ALERT_WAIT_TIME: 87 | return True 88 | # 商品价格有变化且低于折扣 89 | if discount and float(discount) <= DISCOUNT_LIMIT and is_alert == 1 and time_delta.total_seconds() > EMAIL_FIRST_ALERT_WAIT_TIME: 90 | return True 91 | return False 92 | 93 | def query_pm_monitor_item(self, monitor_item_id): 94 | """ 95 | 查询pm_monitor_item表 96 | """ 97 | session = self.DBSession() 98 | record = session.query(PmMonitorItem).filter(PmMonitorItem.id == monitor_item_id).one() 99 | session.close() 100 | return record 101 | 102 | 103 | def query_user_info(self, monitor_item_id): 104 | """ 105 | 通过监控表Id查询用户Id,然后查用户表获取信息 106 | """ 107 | logging.info("查用户表获取信息:{}".format(monitor_item_id)) 108 | 109 | # 查询pm_monitor_item表 110 | session = self.DBSession() 111 | record_pm_monitor_item = session.query(PmMonitorItem).filter(PmMonitorItem.id == monitor_item_id).one() 112 | user_id = record_pm_monitor_item.user_id 113 | logging.info("user_id:{}".format(user_id)) 114 | 115 | # 查询pm_user表 116 | record_pm_user = session.query(PmUser).filter(PmUser.id == user_id).one() 117 | name = record_pm_user.name 118 | email = record_pm_user.email 119 | session.close() 120 | 121 | logging.info("name:{}".format(name)) 122 | logging.info("email:{}".format(email)) 123 | user_info = {"name": name, "email": email} 124 | return user_info 125 | 126 | def update_alert_info(self, monitor_item_id, status): 127 | """ 128 | 修改监控表is_alert状态值 129 | """ 130 | logging.info("更新监控表is_alert状态值开始:{} {}".format(monitor_item_id, status)) 131 | session = self.DBSession() 132 | record = session.query(PmMonitorItem).filter(PmMonitorItem.id == monitor_item_id).one() 133 | record.is_alert = status 134 | session.commit() 135 | session.close() 136 | logging.info("更新监控表is_alert状态值完成") 137 | 138 | def insert_pm_mail_record(self, address, sender, receiver, subject, text, is_sent): 139 | """ 140 | 发送邮件记录 141 | """ 142 | logging.info("插入邮件记录pm_mail_record:{} {} {} {} {} {}".format(address, sender, receiver, subject, text, is_sent)) 143 | session = self.DBSession() 144 | record = PmMailRecord(address=address, _from=sender, to=receiver, subject=subject, content=text, is_sent=is_sent, 145 | gmt_create=datetime.datetime.now(), gmt_modified=datetime.datetime.now()) 146 | session.add(record) 147 | session.commit() 148 | session.close() 149 | 150 | 151 | if __name__ == '__main__': 152 | logging.basicConfig(format="%(asctime)s %(filename)s %(funcName)s %(lineno)s %(levelname)s - %(" 153 | "message)s", datefmt="%Y-%m-%d %H:%M:%S", 154 | level=logging.INFO) 155 | sqlOperator = SqlOperator() 156 | 157 | # sqlOperator.update_pm_monitor_item({'id': "582", 'item_id': "8738639"}, 158 | # {'name': '五月花(May Flower) 抽纸 婴儿柔特级柔厚4层90抽面巾纸*6包(小规格)', 'price': '14.90', 159 | # 'plus_price': None, 'subtitle': '生活就是这样,越努力,越幸运五月花,婴儿柔为优秀的你而生!(此商品不参加上述活动)'} 160 | # , {'max_price': 34.9, 'min_price': 34.2}) 161 | 162 | logging.info(sqlOperator.query_email_alert_needed(1509)) 163 | 164 | # logging.info(sqlOperator.query_user_info(582)) 165 | 166 | # logging.info(sqlOperator.query_pm_monitor_item(582).__dict__) -------------------------------------------------------------------------------- /PriceMonitor/mail.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # coding=utf-8 3 | from email.header import Header 4 | from email.mime.text import MIMEText 5 | from email.utils import parseaddr, formataddr 6 | import smtplib 7 | from os import path 8 | import os 9 | import logging 10 | 11 | 12 | class Mail(object): 13 | # mailbox setting 14 | local_dir = path.dirname(__file__) 15 | with open(os.path.join(local_dir, 'mailbox.txt'), 'r') as f: 16 | mail_setting = f.readlines() 17 | from_addr = mail_setting[0].strip() 18 | password = mail_setting[1].strip() 19 | smtp_server = mail_setting[2].strip() 20 | 21 | def __init__(self, text, sender, receiver, subject, address): 22 | self.text = text 23 | self.sender = sender 24 | self.receiver = receiver 25 | self.subject = subject 26 | self.address = address 27 | self.to_addr = address 28 | # From above to below: mail content, sender nickname, receiver nickname, subject 29 | self.msg = MIMEText(self.text, 'plain', 'utf-8') 30 | self.msg['From'] = self._format_addr(self.sender + '<' + self.from_addr + '>') 31 | self.msg['To'] = self._format_addr(self.receiver + '<' + self.to_addr + '>') 32 | self.msg['Subject'] = Header(self.subject, 'utf-8').encode() 33 | 34 | # format the email address 35 | def _format_addr(self, s): 36 | name, addr = parseaddr(s) 37 | return formataddr((Header(name, 'utf-8').encode(), addr)) 38 | 39 | def send(self): 40 | # server = smtplib.SMTP(self.smtp_server, 25) # 25 normal,465 SSL 41 | server = smtplib.SMTP_SSL(self.smtp_server, 465) 42 | # server.starttls() # SSL required 43 | server.set_debuglevel(1) 44 | server.login(self.from_addr, self.password) 45 | try: 46 | server.sendmail(self.from_addr, [self.to_addr], self.msg.as_string()) 47 | except Exception: 48 | return False 49 | logging.info('----This email\'s info: %s, %s, %s', self.text, self.receiver, self.to_addr) 50 | server.quit() 51 | return True 52 | 53 | 54 | if __name__ == '__main__': 55 | logging.basicConfig(level=logging.DEBUG) 56 | send_email = Mail('test', 'wo', 'ni', 'test', 'xxxxxxx@qq.com') 57 | send_email.send() 58 | -------------------------------------------------------------------------------- /PriceMonitor/mailbox.txt: -------------------------------------------------------------------------------- 1 | xxxxxxxx@xxxxxx.com 2 | xxxxxxx 3 | smtp.qq.com -------------------------------------------------------------------------------- /PriceMonitor/producer_jd_crawl.py: -------------------------------------------------------------------------------- 1 | import json 2 | import pika 3 | 4 | from CONFIG import RABBIT_MQ_HOST 5 | 6 | connection = pika.BlockingConnection(pika.ConnectionParameters(host=RABBIT_MQ_HOST)) 7 | channel = connection.channel() 8 | channel.queue_declare(queue='jd_crawl') 9 | 10 | data = {'id': "1", 'item_id': "100008348542"} 11 | 12 | channel.basic_publish(exchange='', routing_key='jd_crawl', body=json.dumps(data)) 13 | connection.close() 14 | -------------------------------------------------------------------------------- /PriceMonitor/producer_mail.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | 4 | import pika 5 | 6 | from CONFIG import RABBIT_MQ_HOST 7 | 8 | 9 | class ProducerMail: 10 | 11 | @staticmethod 12 | def send_mail_message(data): 13 | connection = pika.BlockingConnection(pika.ConnectionParameters(host=RABBIT_MQ_HOST)) 14 | channel = connection.channel() 15 | channel.queue_declare(queue='mail') 16 | 17 | channel.basic_publish(exchange='', routing_key='mail', body=json.dumps(data)) 18 | connection.close() 19 | 20 | 21 | if __name__ == '__main__': 22 | logging.basicConfig(format="%(asctime)s | %(levelname)s | %(filename)s %(lineno)s | %(message)s", 23 | datefmt="%Y-%m-%d %H:%M:%S", 24 | level=logging.INFO) 25 | data = {'subject': "【主题】", 'address': "xxxxxxxx@foxmail.com", 'msg': "内容", 'from': "发送者", 'to': "接收者", "id": 1} 26 | ProducerMail.send_mail_message(data) 27 | -------------------------------------------------------------------------------- /PriceMonitor/proxy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import random 4 | import time 5 | import redis 6 | import logging 7 | import requests 8 | from CONFIG import PROXY_POOL_IP 9 | USER_AGENT_LIST = [ 10 | "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1", 11 | "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11", 12 | "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6", 13 | "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6", 14 | "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1", 15 | "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5", 16 | "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5", 17 | "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", 18 | "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", 19 | "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3", 20 | "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", 21 | "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3", 22 | "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", 23 | "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", 24 | "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3", 25 | "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3", 26 | "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", 27 | "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24", 28 | "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.132 Safari/537.36", 29 | "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0", 30 | 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', # search engine header 31 | 'Mozilla/5.0 (compatible; Bingbot/2.0; +http://www.bing.com/bingbot.htm)', 32 | 'Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)', 33 | 'DuckDuckBot/1.0; (+http://duckduckgo.com/duckduckbot.html)', 34 | 'Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)', 35 | 'Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)', 36 | 'ia_archiver (+http://www.alexa.com/site/help/webmasters; crawler@alexa.com)' 37 | ] 38 | 39 | 40 | class Proxy(object): 41 | 42 | def get_proxy(self): 43 | r = redis.Redis(host=PROXY_POOL_IP, port=6379, db=0) 44 | while True: 45 | good_proxies = r.srandmember("good_proxies", 1) 46 | if good_proxies: 47 | good_proxies = good_proxies[0].decode("utf-8") # byte to str 48 | good_proxies = {"http": good_proxies, "https": good_proxies} 49 | header = self.get_ua() 50 | return header, good_proxies 51 | else: 52 | logging.critical('No proxy now from remote server, retrying') 53 | time.sleep(5) 54 | 55 | def get_proxy_zhima(self): 56 | url = 'http://webapi.http.zhimacangku.com/getip?num=1&type=2&pro=0' \ 57 | '&city=0&yys=0&port=11&pack=8241&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1®ions=' 58 | while True: 59 | header = self.get_ua() 60 | r = requests.get(url, headers=header, timeout=5) 61 | logging.warning('Zhima Proxy: %s', r.json()) 62 | if not r.json()['data']: 63 | logging.warning('No Zhima Proxy anymore or too fast. Retrying') 64 | time.sleep(5) 65 | continue 66 | try: 67 | proxy_ip = r.json()['data'][0]['ip'] 68 | proxy_port = r.json()['data'][0]['port'] 69 | good_proxies = proxy_ip + ':' + str(proxy_port) 70 | good_proxies = {"http": good_proxies, "https": good_proxies} 71 | logging.info('Zhima get proxy, using proxy: %s', good_proxies) 72 | return header, good_proxies 73 | except: 74 | logging.warning('No Zhima Proxy now. Retrying') 75 | time.sleep(5) 76 | continue 77 | 78 | @staticmethod 79 | def get_ua(): 80 | ua = random.choice(USER_AGENT_LIST) 81 | ua = {'user-agent': ua} # dict 82 | logging.debug('Generating header: %s', ua) 83 | return ua 84 | 85 | 86 | if __name__ == '__main__': 87 | logging.basicConfig(level=logging.DEBUG) 88 | p = Proxy() 89 | p.get_ua() 90 | # p.get_proxy() 91 | p.get_proxy_zhima() 92 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Price-Monitor 3 | 4 | **JD商品价格监控** 5 | 6 | [![License](https://img.shields.io/badge/license-GPLv3-yellowgreen.svg)]() 7 | [![Poweredby](https://img.shields.io/badge/Powered%20by-requests-green.svg)]() 8 | [![Poweredby](https://img.shields.io/badge/Powered%20by-selenium-green.svg)]() 9 | 10 | ## 简介 11 | 12 | 用户自行设定指定商品的监控价格,运行脚本获取价格数据。 13 | 14 | **申明:本脚本没有涉及JD账号登录,没有抓取任何JD敏感信息,仅在手动执行一次脚本时会读取JD公开商品页面的商品名称和价格,如有任何敏感侵权问题,请联系我删除。** 15 | 16 | **申明:本脚本没有涉及JD账号登录,没有抓取任何JD敏感信息,仅在手动执行一次脚本时会读取JD公开商品页面的商品名称和价格,如有任何敏感侵权问题,请联系我删除。** 17 | 18 | **申明:本脚本没有涉及JD账号登录,没有抓取任何JD敏感信息,仅在手动执行一次脚本时会读取JD公开商品页面的商品名称和价格,如有任何敏感侵权问题,请联系我删除。** 19 | 20 | 21 | 22 | ## 核心代码 23 | 24 | 请先使用`pip install -r requirements.txt`安装依赖库 25 | 26 | 你需要的仅仅只是这两个Crawler类: 27 | 28 | - crawler_selenium: (推荐) 使用selenium+chrome访问某东商品单页进行爬取 29 | 30 | - crawler_js.py: 使用requests访问某东商品数据接口进行爬取 31 | 32 | 两个类下方都有测试代码,可以调试,并且都可以接入http/https代理。 33 | 34 | **代码里面包括了商品名称,副标题,PLUS价格,历史最高最低价等。** 35 | 36 | 由于电商经常会更新接口,所以Crawler代码往往具有时效性,若发现代码报错不要慌,自行尝试修改。 37 | 38 | 39 | ### 使用selenium+chrome注意事项 40 | 41 | 需要安装chrome和chromedriver 42 | 43 | 若您使用默认的Selenium+Chrome,您还需要安装好Chrome,以及Selenium用来操控Chrome的ChromeDriver。 44 | 45 | http://npm.taobao.org/mirrors/chromedriver/ 46 | 47 | 若您在Windows下调试本项目,可以将ChromeDriver放置在任何配置了环境变量的目录下,我放在了C:/Windows/chromedriver.exe 48 | 49 | 若您使用Js爬取,不需要任何额外的库 50 | 51 | -------------------------------------------------------------------------------- /docs/Email01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qqxx6661/Price-monitor/ca0b0e6c0054446fb3538c63f597e2562ae97297/docs/Email01.png -------------------------------------------------------------------------------- /docs/Email02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qqxx6661/Price-monitor/ca0b0e6c0054446fb3538c63f597e2562ae97297/docs/Email02.png -------------------------------------------------------------------------------- /docs/Pagedemo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qqxx6661/Price-monitor/ca0b0e6c0054446fb3538c63f597e2562ae97297/docs/Pagedemo.png -------------------------------------------------------------------------------- /docs/Pagedemo2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qqxx6661/Price-monitor/ca0b0e6c0054446fb3538c63f597e2562ae97297/docs/Pagedemo2.png -------------------------------------------------------------------------------- /docs/Pagedemo3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qqxx6661/Price-monitor/ca0b0e6c0054446fb3538c63f597e2562ae97297/docs/Pagedemo3.png -------------------------------------------------------------------------------- /docs/Pagedemo4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qqxx6661/Price-monitor/ca0b0e6c0054446fb3538c63f597e2562ae97297/docs/Pagedemo4.png -------------------------------------------------------------------------------- /docs/SetupEmail.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # 邮箱设置 4 | 5 | 以QQ邮箱为例 6 | 7 | 1. 注册QQ号,申请QQ邮箱,登陆,随后如图所示进入设置-账户 8 | 9 | ![Email01](Email01.png) 10 | 11 | 12 | 2. 下翻至如图所示位置,开启POP3/SMTP服务或IMAP/SMTP服务,会得到加密密钥 13 | 14 | ![Email02](Email02.png) 15 | 16 | 3. 找到本项目文件中PriceMonitor-mailbox.txt文件,自行设置邮箱,大部分邮箱都支持,比如QQ,gamil,校园邮箱,网易等 17 | 18 | - 第一行为发送邮箱地址 19 | - 第二行为发送邮箱密码 20 | - 第三行为邮箱的stmp 21 | 22 | QQ邮箱示例: 23 | ``` 24 | xxxxxxxxxx@qq.com 25 | xxxxxxxx 26 | smtp.qq.com 27 | ``` 28 | 29 | 校园邮箱示例: 30 | ``` 31 | xxxxxxxxx@xxx.edu.cn 32 | xxxxxxxx 33 | stmp.xxx.edu.cn 34 | ``` 35 | 36 | 4.设置成功后,发件邮箱即为此邮箱。 37 | 38 | -------------------------------------------------------------------------------- /docs/Sqlitedemo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qqxx6661/Price-monitor/ca0b0e6c0054446fb3538c63f597e2562ae97297/docs/Sqlitedemo.png -------------------------------------------------------------------------------- /docs/Structure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/qqxx6661/Price-monitor/ca0b0e6c0054446fb3538c63f597e2562ae97297/docs/Structure.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | lxml==4.6.3 2 | requests==2.20.0 3 | urllib3==1.26.5 4 | selenium==3.8.1 5 | redis==3.2.1 6 | PyMySQL==0.8.0 7 | sqlalchemy==1.3.11 8 | pika==1.1.0 9 | pysocks==1.7.1 --------------------------------------------------------------------------------