├── .github └── ISSUE_TEMPLATE │ ├── bug_report.yml │ ├── feature_request.yml │ └── question.md ├── .gitignore ├── LICENSE ├── README.md ├── pyproject.toml └── snscrape ├── __init__.py ├── _cli.py ├── base.py ├── modules ├── __init__.py ├── facebook.py ├── instagram.py ├── mastodon.py ├── reddit.py ├── telegram.py ├── twitter.py ├── vkontakte.py └── weibo.py ├── utils.py └── version.py /.github/ISSUE_TEMPLATE/bug_report.yml: -------------------------------------------------------------------------------- 1 | name: Bug report 2 | description: Are you experiencing a problem? Create a report to help us improve! 3 | labels: 'bug' 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | ## Self Check 9 | - Try searching existing GitHub Issues (open or closed) for similar issues. 10 | - type: textarea 11 | validations: 12 | required: true 13 | attributes: 14 | label: Describe the bug 15 | description: A clear description of what the bug is. 16 | placeholder: e.g. I see an AssertionError when trying to scrape a Twitter user! 17 | - type: textarea 18 | validations: 19 | required: true 20 | attributes: 21 | label: How to reproduce 22 | description: | 23 | How to reproduce the problem. 24 | This should be a minimal reproducible example, i.e. the shortest possible code or the smallest number of steps that still causes the error. 25 | placeholder: e.g. I can reproduce this issue by scraping the textfiles user with the twitter-user scraper. 26 | - type: textarea 27 | validations: 28 | required: true 29 | attributes: 30 | label: Expected behaviour 31 | description: A brief description of what should happen. 32 | - type: textarea 33 | attributes: 34 | label: Screenshots and recordings 35 | description: | 36 | If applicable, add screenshots or videos to help explain your problem. (Videos should be as short as possible! Avoid watermarks too.) 37 | - type: input 38 | validations: 39 | required: true 40 | attributes: 41 | label: Operating system 42 | description: Include the version too, please! 43 | placeholder: e.g. Windows 10, Ubuntu 20.04, macOS 10.15... 44 | - type: input 45 | validations: 46 | required: true 47 | attributes: 48 | label: | 49 | Python version: output of `python3 --version` 50 | - type: input 51 | validations: 52 | required: true 53 | attributes: 54 | label: | 55 | snscrape version: output of `snscrape --version` 56 | - type: input 57 | validations: 58 | required: true 59 | attributes: 60 | label: Scraper 61 | placeholder: e.g. twitter-user, reddit-search, TwitterSearchScraper, ... 62 | - type: dropdown 63 | validations: 64 | required: true 65 | attributes: 66 | label: How are you using snscrape? 67 | options: ['CLI (`snscrape ...` as a command, e.g. in a terminal)', 'Module (`import snscrape.modules.something` in Python code)'] 68 | - type: textarea 69 | validations: 70 | required: false 71 | attributes: 72 | label: Backtrace 73 | description: What is the error snscrape gives you, if any? 74 | - type: textarea 75 | validations: 76 | required: false 77 | attributes: 78 | label: Log output 79 | description: | 80 | Insert here the debug log of snscrape. 81 | If you use the CLI, add the global options `-vv` to the command, e.g. `snscrape -vv twitter-search ...`. 82 | If you use the module, set the debug level in your Python code before any use of snscrape: `import logging; logging.basicConfig(level = logging.DEBUG)`. 83 | If you already use `logging` in your own code, you may need to adjust the level there instead. 84 | - type: textarea 85 | validations: 86 | required: false 87 | attributes: 88 | label: Dump of locals 89 | description: | 90 | Here attach the dump of your snscrape locals, if it's a crash. (snscrape should tell you the path). 91 | Please note that it may contain identifying info such as IP address, if the website returns that. 92 | You can also optionally request to exchange the file in private. 93 | Finally, if snscrape didn't crash, leave this field blank. 94 | - type: textarea 95 | attributes: 96 | label: Additional context 97 | description: Add any other context about the problem here. 98 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: Feature Request 2 | description: Want a feature? Ask; we don't bite! 3 | labels: 'enhancement' 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | ## Self Check 9 | - Try searching existing GitHub Issues (open or closed) for similar issues. 10 | - type: textarea 11 | validations: 12 | required: true 13 | attributes: 14 | label: Describe the feature 15 | description: A clear description of what the feature is. 16 | - type: textarea 17 | validations: 18 | required: false 19 | attributes: 20 | label: Would this fix a problem you're experiencing? If so, specify. 21 | - type: textarea 22 | attributes: 23 | label: Did you consider other alternatives? 24 | description: If so, specify 25 | - type: input 26 | attributes: 27 | label: Additional context 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: Ask away! (Do not use this for bugs or features.) 4 | labels: 'question' 5 | 6 | --- 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | /dist/ 3 | /snscrape.egg-info/ 4 | /.eggs/ 5 | -------------------------------------------------------------------------------- /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 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # snscrape 2 | snscrape is a scraper for social networking services (SNS). It scrapes things like user profiles, hashtags, or searches and returns the discovered items, e.g. the relevant posts. 3 | 4 | The following services are currently supported: 5 | 6 | * Facebook: user profiles, groups, and communities (aka visitor posts) 7 | * Instagram: user profiles, hashtags, and locations 8 | * Mastodon: user profiles and toots (single or thread) 9 | * Reddit: users, subreddits, and searches (via Pushshift) 10 | * Telegram: channels 11 | * Twitter: users, user profiles, hashtags, searches (live tweets, top tweets, and users), tweets (single or surrounding thread), list posts, communities, and trends 12 | * VKontakte: user profiles 13 | * Weibo (Sina Weibo): user profiles 14 | 15 | ## Requirements 16 | snscrape requires Python 3.8 or higher. The Python package dependencies are installed automatically when you install snscrape. 17 | 18 | Note that one of the dependencies, lxml, also requires libxml2 and libxslt to be installed. 19 | 20 | ## Installation 21 | pip3 install snscrape 22 | 23 | If you want to use the development version: 24 | 25 | pip3 install git+https://github.com/JustAnotherArchivist/snscrape.git 26 | 27 | ## Usage 28 | ### CLI 29 | The generic syntax of snscrape's CLI is: 30 | 31 | snscrape [GLOBAL-OPTIONS] SCRAPER-NAME [SCRAPER-OPTIONS] [SCRAPER-ARGUMENTS...] 32 | 33 | `snscrape --help` and `snscrape SCRAPER-NAME --help` provide details on the options and arguments. `snscrape --help` also lists all available scrapers. 34 | 35 | The default output of the CLI is the URL of each result. 36 | 37 | Some noteworthy global options are: 38 | 39 | * `--jsonl` to get output as JSONL. This includes all information extracted by snscrape (e.g. message content, datetime, images; details vary by scraper). 40 | * `--max-results NUMBER` to only return the first `NUMBER` results. 41 | * `--with-entity` to get an item on the entity being scraped, e.g. the user or channel. This is not supported on all scrapers. (You can use this together with `--max-results 0` to only fetch the entity info.) 42 | 43 | #### Examples 44 | Collect all tweets by Jason Scott (@textfiles): 45 | 46 | snscrape twitter-user textfiles 47 | 48 | It's usually useful to redirect the output to a file for further processing, e.g. in bash using the filename `twitter-@textfiles`: 49 | 50 | ```bash 51 | snscrape twitter-user textfiles >twitter-@textfiles 52 | ``` 53 | 54 | To get the latest 100 tweets with the hashtag #archiveteam: 55 | 56 | snscrape --max-results 100 twitter-hashtag archiveteam 57 | 58 | ### Library 59 | It is also possible to use snscrape as a library in Python, but this is currently undocumented. 60 | 61 | ## Issue reporting 62 | If you discover an issue with snscrape, please report it at . If you use the CLI, please run snscrape with `-vv` and include the log output in the issue. If you use snscrape as a module, please enable debug-level logging using `import logging; logging.basicConfig(level = logging.DEBUG)` (before using snscrape at all) and include the log output in the issue. 63 | 64 | ### Dump files 65 | In some cases, debugging may require more information than is available in the log. The CLI has a `--dump-locals` option that enables dumping all local variables within snscrape based on important log messages (rather than, by default, only on crashes). Note that the dump files may contain sensitive information in some cases and could potentially be used to identify you (e.g. if the service includes your IP address in its response). If you prefer to arrange a file transfer privately, just mention that in the issue. 66 | 67 | ## License 68 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 69 | 70 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 71 | 72 | You should have received a copy of the GNU General Public License along with this program. If not, see . 73 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ['setuptools>=61', 'setuptools_scm>=6.2'] 3 | build-backend = 'setuptools.build_meta' 4 | 5 | [tool.setuptools] 6 | packages = ['snscrape', 'snscrape.modules'] 7 | 8 | [tool.setuptools_scm] 9 | 10 | [project] 11 | name = 'snscrape' 12 | description = 'A social networking service scraper' 13 | readme = 'README.md' 14 | authors = [{name = 'JustAnotherArchivist'}] 15 | classifiers = [ 16 | 'Development Status :: 4 - Beta', 17 | 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 18 | 'Programming Language :: Python :: 3.8', 19 | 'Programming Language :: Python :: 3.9', 20 | 'Programming Language :: Python :: 3.10', 21 | 'Programming Language :: Python :: 3.11', 22 | ] 23 | dependencies = [ 24 | 'requests[socks]', 25 | 'lxml', 26 | 'beautifulsoup4', 27 | 'pytz; python_version < "3.9.0"', 28 | 'filelock', 29 | ] 30 | requires-python = '~=3.8' 31 | dynamic = ['version'] 32 | 33 | [project.urls] 34 | repository = "https://github.com/JustAnotherArchivist/snscrape" 35 | 36 | [project.scripts] 37 | snscrape = 'snscrape._cli:main' 38 | -------------------------------------------------------------------------------- /snscrape/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JustAnotherArchivist/snscrape/614d4c2029a62d348ca56598f87c425966aaec66/snscrape/__init__.py -------------------------------------------------------------------------------- /snscrape/_cli.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import collections 3 | import contextlib 4 | import dataclasses 5 | import datetime 6 | import importlib.metadata 7 | import inspect 8 | import logging 9 | import os 10 | import requests 11 | # Imported in parse_args() after setting up the logger: 12 | #import snscrape.base 13 | #import snscrape.modules 14 | #import snscrape.version 15 | import sys 16 | import tempfile 17 | 18 | 19 | ## Logging 20 | dumpLocals = False 21 | logger = logging # Replaced below after setting the logger class 22 | 23 | 24 | class Logger(logging.Logger): 25 | def _log_with_stack(self, level, *args, **kwargs): 26 | super().log(level, *args, **kwargs) 27 | if dumpLocals and not kwargs.get('extra', {}).get('_snscrapeSuppressDumpLocals', False): 28 | stack = inspect.stack() 29 | if len(stack) >= 3: 30 | name = _dump_stack_and_locals(stack[2:][::-1]) 31 | super().log(level, f'Dumped stack and locals to {name}') 32 | 33 | def warning(self, *args, **kwargs): 34 | self._log_with_stack(logging.WARNING, *args, **kwargs) 35 | 36 | def error(self, *args, **kwargs): 37 | self._log_with_stack(logging.ERROR, *args, **kwargs) 38 | 39 | def critical(self, *args, **kwargs): 40 | self._log_with_stack(logging.CRITICAL, *args, **kwargs) 41 | 42 | def log(self, level, *args, **kwargs): 43 | if level >= logging.WARNING: 44 | self._log_with_stack(level, *args, **kwargs) 45 | else: 46 | super().log(level, *args, **kwargs) 47 | 48 | 49 | def _requests_request_repr(name, request): 50 | ret = [] 51 | ret.append(f'{name} = {request!r}') 52 | ret.append(f'\n {name}.method = {request.method}') 53 | ret.append(f'\n {name}.url = {request.url}') 54 | ret.append(f'\n {name}.headers = \\') 55 | for field in request.headers: 56 | ret.append(f'\n {field} = {_repr("_", request.headers[field])}') 57 | for attr in ('body', 'params', 'data'): 58 | if hasattr(request, attr) and getattr(request, attr): 59 | ret.append(f'\n {name}.{attr} = ') 60 | ret.append(_repr('_', getattr(request, attr)).replace('\n', '\n ')) 61 | return ''.join(ret) 62 | 63 | 64 | def _requests_response_repr(name, response, withHistory = True): 65 | ret = [] 66 | ret.append(f'{name} = {response!r}') 67 | ret.append(f'\n {name}.url = {response.url}') 68 | ret.append(f'\n {name}.request = ') 69 | ret.append(_repr('_', response.request).replace('\n', '\n ')) 70 | if withHistory and response.history: 71 | ret.append(f'\n {name}.history = [') 72 | for previousResponse in response.history: 73 | ret.append('\n ') 74 | ret.append(_requests_response_repr('_', previousResponse, withHistory = False).replace('\n', '\n ')) 75 | ret.append('\n ]') 76 | ret.append(f'\n {name}.status_code = {response.status_code}') 77 | ret.append(f'\n {name}.headers = \\') 78 | for field in response.headers: 79 | ret.append(f'\n {field} = {_repr("_", response.headers[field])}') 80 | ret.append(f'\n {name}.content = {_repr("_", response.content)}') 81 | return ''.join(ret) 82 | 83 | 84 | def _requests_exception_repr(name, exc): 85 | ret = [] 86 | ret.append(f'{name} = {exc!r}') 87 | ret.append('\n ' + _repr(f'{name}.request', exc.request).replace('\n', '\n ')) 88 | ret.append('\n ' + _repr(f'{name}.response', exc.response).replace('\n', '\n ')) 89 | return ''.join(ret) 90 | 91 | 92 | def _repr(name, value): 93 | if type(value) is requests.Response: 94 | return _requests_response_repr(name, value) 95 | if type(value) in (requests.PreparedRequest, requests.Request): 96 | return _requests_request_repr(name, value) 97 | if isinstance(value, requests.exceptions.RequestException): 98 | return _requests_exception_repr(name, value) 99 | if isinstance(value, dict): 100 | return f'{name} = <{type(value).__module__}.{type(value).__name__}>\n ' + \ 101 | '\n '.join(_repr(f'{name}[{k!r}]', v).replace('\n', '\n ') for k, v in value.items()) 102 | if isinstance(value, (list, tuple, collections.deque)) and not all(isinstance(v, (int, str)) for v in value): 103 | return f'{name} = <{type(value).__module__}.{type(value).__name__}>\n ' + \ 104 | '\n '.join(_repr(f'{name}[{i}]', v).replace('\n', '\n ') for i, v in enumerate(value)) 105 | if dataclasses.is_dataclass(value) and not isinstance(value, type): 106 | return f'{name} = <{type(value).__module__}.{type(value).__name__}>\n ' + \ 107 | '\n '.join(_repr(f'{name}.{f.name}', f.name) + ' = ' + _repr(f'{name}.{f.name}', getattr(value, f.name)).replace('\n', '\n ') for f in dataclasses.fields(value)) 108 | valueRepr = f'{name} = {value!r}' 109 | if '\n' in valueRepr: 110 | return ''.join(['\\\n ', valueRepr.replace('\n', '\n ')]) 111 | return valueRepr 112 | 113 | 114 | @contextlib.contextmanager 115 | def _dump_locals_on_exception(): 116 | try: 117 | yield 118 | except Exception as e: 119 | trace = inspect.trace() 120 | if len(trace) >= 2: 121 | name = _dump_stack_and_locals(trace[1:], exc = e) 122 | logger.fatal(f'Dumped stack and locals to {name}', extra = {'_snscrapeSuppressDumpLocals': True}) 123 | raise 124 | 125 | 126 | def _dump_stack_and_locals(trace, exc = None): 127 | with tempfile.NamedTemporaryFile('w', prefix = 'snscrape_locals_', delete = False) as fp: 128 | if exc is not None: 129 | fp.write('Exception:\n') 130 | fp.write(f' {type(exc).__module__}.{type(exc).__name__}: {exc!s}\n') 131 | fp.write(f' args: {exc.args!r}\n') 132 | fp.write('\n') 133 | 134 | fp.write('Stack:\n') 135 | for frameRecord in trace: 136 | fp.write(f' File "{frameRecord.filename}", line {frameRecord.lineno}, in {frameRecord.function}\n') 137 | if frameRecord.code_context is not None: 138 | for line in frameRecord.code_context: 139 | fp.write(f' {line.strip()}\n') 140 | fp.write('\n') 141 | 142 | modules = [inspect.getmodule(frameRecord[0]) for frameRecord in trace] 143 | for i, (module, frameRecord) in enumerate(zip(modules, trace)): 144 | if module is None: 145 | # Module-less frame, e.g. dataclass.__init__ 146 | for j in reversed(range(i)): 147 | if modules[j] is not None: 148 | break 149 | else: 150 | # No previous module scope 151 | continue 152 | module = modules[j] 153 | if not module.__name__.startswith('snscrape.') and module.__name__ != 'snscrape': 154 | continue 155 | locals_ = frameRecord[0].f_locals 156 | fp.write(f'Locals from file "{frameRecord.filename}", line {frameRecord.lineno}, in {frameRecord.function}:\n') 157 | for variableName in locals_: 158 | variable = locals_[variableName] 159 | varRepr = _repr(variableName, variable) 160 | fp.write(f' {variableName} {type(variable)} = ') 161 | fp.write(varRepr.replace('\n', '\n ')) 162 | fp.write('\n') 163 | fp.write('\n') 164 | if 'self' in locals_ and hasattr(locals_['self'], '__dict__'): 165 | fp.write('Object dict:\n') 166 | fp.write(repr(locals_['self'].__dict__)) 167 | fp.write('\n\n') 168 | name = fp.name 169 | return name 170 | 171 | 172 | def parse_datetime_arg(arg): 173 | for format in ('%Y-%m-%d %H:%M:%S %z', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %z', '%Y-%m-%d'): 174 | try: 175 | d = datetime.datetime.strptime(arg, format) 176 | except ValueError: 177 | continue 178 | else: 179 | if d.tzinfo is None: 180 | return d.replace(tzinfo = datetime.timezone.utc) 181 | return d 182 | # Try treating it as a unix timestamp 183 | try: 184 | d = datetime.datetime.fromtimestamp(int(arg), datetime.timezone.utc) 185 | except ValueError: 186 | pass 187 | else: 188 | return d 189 | raise argparse.ArgumentTypeError(f'Cannot parse {arg!r} into a datetime object') 190 | 191 | 192 | def parse_format(arg): 193 | # Replace '{' by '{0.' to use properties of the item, but keep '{{' intact 194 | parts = arg.split('{') 195 | out = '' 196 | it = iter(zip(parts, parts[1:])) 197 | for part, nextPart in it: 198 | out += part 199 | if nextPart == '': # Double brace 200 | out += '{{' 201 | next(it) 202 | else: # Single brace 203 | out += '{0.' 204 | out += parts[-1] 205 | return out 206 | 207 | 208 | class CitationAction(argparse.Action): 209 | def __init__(self, option_strings, dest = argparse.SUPPRESS, *args, default = argparse.SUPPRESS, **kwargs): 210 | super().__init__(option_strings, dest, *args, **kwargs) 211 | 212 | def __call__(self, parser, namespace, values, optionString): 213 | try: 214 | m = importlib.metadata.metadata('snscrape') 215 | except importlib.metadata.PackageNotFoundError: 216 | print('Error: could not find snscrape installation. --citation does not work without the package being installed.', file = sys.stderr) 217 | parser.exit(1) 218 | print(f'Author: {m["author"]}') 219 | print(f'Title: {m["name"]}: {m["summary"]}') 220 | print(f'URL: {m["home-page"]}') 221 | print(f'Version: {m["version"]}') 222 | print(f'Date: 2018‒{m["version"].split(".", 3)[3][:4]}') 223 | 224 | if '.dev' in m['version']: 225 | print() 226 | print('WARNING! You are running a development version. The date range may be incorrect. Please adjust the upper end of the range to the year of the commit.') 227 | 228 | parser.exit() 229 | 230 | 231 | def parse_args(): 232 | import snscrape.base 233 | import snscrape.modules 234 | import snscrape.version 235 | 236 | parser = argparse.ArgumentParser(formatter_class = argparse.ArgumentDefaultsHelpFormatter) 237 | parser.add_argument('--version', action = 'version', version = f'snscrape {snscrape.version.__version__}') 238 | parser.add_argument('--citation', action = CitationAction, nargs = 0, help = 'Display recommended citation information and exit') 239 | parser.add_argument('-v', '--verbose', '--verbosity', dest = 'verbosity', action = 'count', default = 0, help = 'Increase output verbosity') 240 | parser.add_argument('--dump-locals', dest = 'dumpLocals', action = 'store_true', default = False, help = 'Dump local variables on serious log messages (warnings or higher)') 241 | parser.add_argument('--retry', '--retries', dest = 'retries', type = int, default = 3, metavar = 'N', 242 | help = 'When the connection fails or the server returns an unexpected response, retry up to N times with an exponential backoff') 243 | parser.add_argument('-n', '--max-results', dest = 'maxResults', type = lambda x: int(x) if int(x) >= 0 else parser.error('--max-results N must be zero or positive'), metavar = 'N', help = 'Only return the first N results') 244 | group = parser.add_mutually_exclusive_group(required = False) 245 | group.add_argument('-f', '--format', dest = 'format', type = parse_format, default = None, help = 'Output format') 246 | group.add_argument('--jsonl', dest = 'jsonl', action = 'store_true', default = False, help = 'Output JSONL') 247 | group.add_argument('--jsonl-for-buggy-int-parser', dest = 'jsonlForBuggyIntParser', action = 'store_true', default = False, help = 'Output JSONL and insert extra string fields into objects for integers exceeding double precision limits') 248 | parser.add_argument('--with-entity', dest = 'withEntity', action = 'store_true', default = False, help = 'Include the entity (e.g. user, channel) as the first output item') 249 | parser.add_argument('--since', type = parse_datetime_arg, metavar = 'DATETIME', help = 'Only return results newer than DATETIME') 250 | parser.add_argument('--progress', action = 'store_true', default = False, help = 'Report progress on stderr') 251 | 252 | subparsers = parser.add_subparsers(dest = 'scraper', metavar = 'SCRAPER', title = 'scrapers', required = True) 253 | classes = snscrape.base.Scraper.__subclasses__() 254 | scrapers = {} 255 | for cls in classes: 256 | if cls.name is not None: 257 | scrapers[cls.name] = cls 258 | classes.extend(cls.__subclasses__()) 259 | for scraper, cls in sorted(scrapers.items()): 260 | subparser = subparsers.add_parser(cls.name, help = '', formatter_class = argparse.ArgumentDefaultsHelpFormatter) 261 | cls._cli_setup_parser(subparser) 262 | subparser.set_defaults(cls = cls) 263 | 264 | args = parser.parse_args() 265 | 266 | if not args.withEntity and args.maxResults == 0: 267 | parser.error('--max-results 0 is only valid when used with --with-entity') 268 | if args.jsonlForBuggyIntParser: 269 | args.jsonl = True 270 | 271 | return args 272 | 273 | 274 | def setup_logging(): 275 | logging.setLoggerClass(Logger) 276 | global logger 277 | logger = logging.getLogger(__name__) 278 | 279 | 280 | def configure_logging(verbosity, dumpLocals_): 281 | global dumpLocals 282 | dumpLocals = dumpLocals_ 283 | 284 | rootLogger = logging.getLogger() 285 | 286 | # Set level 287 | if verbosity > 0: 288 | level = logging.INFO if verbosity == 1 else logging.DEBUG 289 | rootLogger.setLevel(level) 290 | for handler in rootLogger.handlers: 291 | handler.setLevel(level) 292 | 293 | # Create formatter 294 | formatter = logging.Formatter('{asctime}.{msecs:03.0f} {levelname} {name} {message}', datefmt = '%Y-%m-%d %H:%M:%S', style = '{') 295 | 296 | # Remove existing handlers 297 | for handler in rootLogger.handlers: 298 | rootLogger.removeHandler(handler) 299 | 300 | # Add stream handler 301 | handler = logging.StreamHandler() 302 | handler.setFormatter(formatter) 303 | rootLogger.addHandler(handler) 304 | 305 | 306 | def main(): 307 | setup_logging() 308 | args = parse_args() 309 | configure_logging(args.verbosity, args.dumpLocals) 310 | scraper = args.cls._cli_from_args(args) 311 | 312 | i = 0 313 | with _dump_locals_on_exception(): 314 | try: 315 | if args.withEntity and (entity := scraper.entity): 316 | if args.jsonl: 317 | print(entity.json(forBuggyIntParser = args.jsonlForBuggyIntParser)) 318 | else: 319 | print(entity) 320 | if args.maxResults == 0: 321 | logger.info('Exiting after 0 results') 322 | return 323 | for i, item in enumerate(scraper.get_items(), start = 1): 324 | if args.since is not None and item.date < args.since: 325 | logger.info(f'Exiting due to reaching older results than {args.since}') 326 | break 327 | if args.jsonl: 328 | print(item.json(forBuggyIntParser = args.jsonlForBuggyIntParser)) 329 | elif args.format is not None: 330 | print(args.format.format(item)) 331 | else: 332 | print(item) 333 | if args.progress and i % 100 == 0: 334 | print(f'Scraping, {i} results so far', file = sys.stderr) 335 | if args.maxResults and i >= args.maxResults: 336 | logger.info(f'Exiting after {i} results') 337 | if args.progress: 338 | print(f'Stopped scraping after {i} results due to --max-results', file = sys.stderr) 339 | break 340 | else: 341 | logger.info(f'Done, found {i} results') 342 | if args.progress: 343 | print(f'Finished, {i} results', file = sys.stderr) 344 | except BrokenPipeError: 345 | os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno()) 346 | sys.exit(1) 347 | -------------------------------------------------------------------------------- /snscrape/base.py: -------------------------------------------------------------------------------- 1 | __all__ = ['DeprecatedFeatureWarning', 'Item', 'IntWithGranularity', 'ScraperException', 'EntityUnavailable', 'Scraper'] 2 | 3 | 4 | import abc 5 | import copy 6 | import dataclasses 7 | import datetime 8 | import enum 9 | import functools 10 | import json 11 | import logging 12 | import random 13 | import requests 14 | import requests.adapters 15 | import snscrape.utils 16 | import snscrape.version 17 | import urllib3.connection 18 | import time 19 | import warnings 20 | 21 | 22 | _logger = logging.getLogger(__name__) 23 | 24 | 25 | class DeprecatedFeatureWarning(FutureWarning): 26 | pass 27 | 28 | 29 | class _DeprecatedProperty: 30 | def __init__(self, name, repl, replStr): 31 | self.name = name 32 | self.repl = repl 33 | self.replStr = replStr 34 | 35 | def __get__(self, obj, objType): 36 | if obj is None: # if the access is through the class using _DeprecatedProperty rather than an instance of the class: 37 | return self 38 | warnings.warn(f'{self.name} is deprecated, use {self.replStr} instead', DeprecatedFeatureWarning, stacklevel = 2) 39 | return self.repl(obj) 40 | 41 | 42 | def _json_serialise_datetime_enum(obj): 43 | '''A JSON serialiser that converts datetime.datetime and datetime.date objects to ISO-8601 strings and enum.Enum objects to their values.''' 44 | 45 | if isinstance(obj, (datetime.datetime, datetime.date)): 46 | return obj.isoformat() 47 | if isinstance(obj, enum.Enum): 48 | return obj.value 49 | raise TypeError(f'Object of type {type(obj)} is not JSON serializable') 50 | 51 | 52 | def _json_dataclass_to_dict(obj, forBuggyIntParser = False): 53 | if isinstance(obj, _JSONDataclass) or dataclasses.is_dataclass(obj): 54 | out = {} 55 | out['_type'] = f'{type(obj).__module__}.{type(obj).__name__}' 56 | for field in dataclasses.fields(obj): 57 | assert field.name != '_type' 58 | if field.name.startswith('_'): 59 | continue 60 | out[field.name] = _json_dataclass_to_dict(getattr(obj, field.name), forBuggyIntParser = forBuggyIntParser) 61 | # Add properties 62 | for k in dir(obj): 63 | if isinstance(getattr(type(obj), k, None), (property, _DeprecatedProperty)): 64 | assert k != '_type' 65 | if k.startswith('_'): 66 | continue 67 | out[k] = _json_dataclass_to_dict(getattr(obj, k), forBuggyIntParser = forBuggyIntParser) 68 | elif isinstance(obj, (tuple, list)): 69 | return type(obj)(_json_dataclass_to_dict(x, forBuggyIntParser = forBuggyIntParser) for x in obj) 70 | elif isinstance(obj, dict): 71 | out = {_json_dataclass_to_dict(k, forBuggyIntParser = forBuggyIntParser): _json_dataclass_to_dict(v, forBuggyIntParser = forBuggyIntParser) for k, v in obj.items()} 72 | elif isinstance(obj, set): 73 | return {_json_dataclass_to_dict(v, forBuggyIntParser = forBuggyIntParser) for v in obj} 74 | else: 75 | return copy.deepcopy(obj) 76 | # Transform IntWithGranularity and handle buggy int parser output 77 | for key, value in list(out.items()): # Modifying the dict below, so make a copy first 78 | if isinstance(value, IntWithGranularity): 79 | out[key] = int(value) 80 | assert f'{key}.granularity' not in out, f'Granularity collision on {key}.granularity' 81 | out[f'{key}.granularity'] = value.granularity 82 | elif forBuggyIntParser and isinstance(value, int) and abs(value) > 2**53: 83 | assert f'{key}.str' not in out, f'Buggy int collision on {key}.str' 84 | out[f'{key}.str'] = str(value) 85 | return out 86 | 87 | 88 | @dataclasses.dataclass 89 | class _JSONDataclass: 90 | '''A base class for dataclasses for conversion to JSON''' 91 | 92 | def json(self, forBuggyIntParser = False): 93 | ''' 94 | Convert the object to a JSON string 95 | 96 | If forBuggyIntParser is True, emit JSON for parsers that can't correctly decode integers exceeding the limits of double-precision IEEE 754 floating point numbers. 97 | Specifically, each field x containing an integer with a magnitude above 2**53 results in an additional field x.str with the value as a string. 98 | ''' 99 | 100 | with warnings.catch_warnings(): 101 | warnings.filterwarnings(action = 'ignore', category = DeprecatedFeatureWarning) 102 | out = _json_dataclass_to_dict(self, forBuggyIntParser = forBuggyIntParser) 103 | assert '_snscrape' not in out, 'Metadata collision on _snscrape' 104 | out['_snscrape'] = snscrape.version.__version__ 105 | return json.dumps(out, default = _json_serialise_datetime_enum) 106 | 107 | 108 | @dataclasses.dataclass 109 | class Item(_JSONDataclass): 110 | '''An abstract base class for an item returned by the scraper. 111 | 112 | An item can really be anything. The string representation should be useful for the CLI output (e.g. a direct URL for the item). 113 | ''' 114 | 115 | @abc.abstractmethod 116 | def __str__(self): 117 | pass 118 | 119 | 120 | class IntWithGranularity(int): 121 | '''A number with an associated granularity 122 | 123 | For example, an IntWithGranularity(42000, 1000) represents a number on the order of 42000 with two significant digits, i.e. something counted with a granularity of 1000. 124 | ''' 125 | 126 | def __new__(cls, value, granularity, *args, **kwargs): 127 | obj = super().__new__(cls, value, *args, **kwargs) 128 | obj.granularity = granularity 129 | return obj 130 | 131 | def __reduce__(self): 132 | return (IntWithGranularity, (int(self), self.granularity)) 133 | 134 | 135 | def _random_user_agent(): 136 | def lerp(a1, b1, a2, b2, n): 137 | return (n - a1) / (b1 - a1) * (b2 - a2) + a2 138 | version = int(lerp(datetime.date(2023, 3, 7).toordinal(), datetime.date(2030, 9, 24).toordinal(), 111, 200, datetime.date.today().toordinal())) 139 | version += random.randint(-5, 1) 140 | version = max(version, 101) 141 | return f'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{version}.0.0.0 Safari/537.36' 142 | _DEFAULT_USER_AGENT = _random_user_agent() 143 | 144 | 145 | class _HTTPSAdapter(requests.adapters.HTTPAdapter): 146 | def init_poolmanager(self, *args, **kwargs): 147 | super().init_poolmanager(*args, **kwargs) 148 | #FIXME: Uses private urllib3.PoolManager attribute pool_classes_by_scheme. 149 | try: 150 | self.poolmanager.pool_classes_by_scheme['https'].ConnectionCls = _HTTPSConnection 151 | except (AttributeError, KeyError) as e: 152 | _logger.debug(f'Could not install TLS cipher logger: {type(e).__module__}.{type(e).__name__} {e!s}') 153 | 154 | 155 | class _HTTPSConnection(urllib3.connection.HTTPSConnection): 156 | def connect(self, *args, **kwargs): 157 | conn = super().connect(*args, **kwargs) 158 | #FIXME: Uses undocumented attribute self.sock and beyond. 159 | try: 160 | _logger.debug(f'Connected to: {self.sock.getpeername()}') 161 | except AttributeError: 162 | # self.sock might be a urllib3.util.ssltransport.SSLTransport, which lacks getpeername. 163 | pass 164 | try: 165 | _logger.debug(f'Connection cipher: {self.sock.cipher()}') 166 | except AttributeError: 167 | # Shouldn't be possible, but better safe than sorry. 168 | pass 169 | return conn 170 | 171 | 172 | class ScraperException(Exception): 173 | pass 174 | 175 | 176 | class EntityUnavailable(ScraperException): 177 | '''The target entity of the scrape is unavailable, possibly because it does not exist or was suspended.''' 178 | 179 | 180 | class Scraper: 181 | '''An abstract base class for a scraper.''' 182 | 183 | name = None 184 | 185 | def __init__(self, *, retries = 3, proxies = None): 186 | self._retries = retries 187 | self._proxies = proxies 188 | self._session = requests.Session() 189 | self._session.mount('https://', _HTTPSAdapter()) 190 | 191 | @abc.abstractmethod 192 | def get_items(self): 193 | '''Iterator yielding Items.''' 194 | 195 | pass 196 | 197 | def _get_entity(self): 198 | '''Get the entity behind the scraper, if any. 199 | 200 | This is the method implemented by subclasses for doing the actual retrieval/entity object creation. For accessing the scraper's entity, use the entity property. 201 | ''' 202 | 203 | return None 204 | 205 | @functools.cached_property 206 | def entity(self): 207 | return self._get_entity() 208 | 209 | def _request(self, method, url, params = None, data = None, headers = None, timeout = 10, responseOkCallback = None, allowRedirects = True, proxies = None): 210 | if not headers: 211 | headers = {} 212 | if 'User-Agent' not in headers: 213 | headers['User-Agent'] = _DEFAULT_USER_AGENT 214 | proxies = proxies or self._proxies or {} 215 | errors = [] 216 | for attempt in range(self._retries + 1): 217 | # The request is newly prepared on each retry because of potential cookie updates. 218 | req = self._session.prepare_request(requests.Request(method, url, params = params, data = data, headers = headers)) 219 | environmentSettings = self._session.merge_environment_settings(req.url, proxies, None, None, None) 220 | _logger.info(f'Retrieving {req.url}') 221 | _logger.debug(f'... with headers: {headers!r}') 222 | if data: 223 | _logger.debug(f'... with data: {data!r}') 224 | if environmentSettings: 225 | _logger.debug(f'... with environmentSettings: {environmentSettings!r}') 226 | try: 227 | r = self._session.send(req, allow_redirects = allowRedirects, timeout = timeout, **environmentSettings) 228 | except requests.exceptions.RequestException as exc: 229 | if attempt < self._retries: 230 | retrying = ', retrying' 231 | level = logging.INFO 232 | else: 233 | retrying = '' 234 | level = logging.ERROR 235 | _logger.log(level, f'Error retrieving {req.url}: {exc!r}{retrying}') 236 | errors.append(repr(exc)) 237 | else: 238 | redirected = f' (redirected to {r.url})' if r.history else '' 239 | _logger.info(f'Retrieved {req.url}{redirected}: {r.status_code}') 240 | _logger.debug(f'... with response headers: {r.headers!r}') 241 | if r.history: 242 | for i, redirect in enumerate(r.history): 243 | _logger.debug(f'... request {i}: {redirect.request.url}: {redirect.status_code} (Location: {redirect.headers.get("Location")})') 244 | _logger.debug(f'... ... with response headers: {redirect.headers!r}') 245 | if responseOkCallback is not None: 246 | success, msg = responseOkCallback(r) 247 | errors.append(msg) 248 | else: 249 | success, msg = (True, None) 250 | msg = f': {msg}' if msg else '' 251 | 252 | if success: 253 | _logger.debug(f'{req.url} retrieved successfully{msg}') 254 | return r 255 | else: 256 | if attempt < self._retries: 257 | retrying = ', retrying' 258 | level = logging.INFO 259 | else: 260 | retrying = '' 261 | level = logging.ERROR 262 | _logger.log(level, f'Error retrieving {req.url}{msg}{retrying}') 263 | if attempt < self._retries: 264 | sleepTime = 1.0 * 2**attempt # exponential backoff: sleep 1 second after first attempt, 2 after second, 4 after third, etc. 265 | _logger.info(f'Waiting {sleepTime:.0f} seconds') 266 | time.sleep(sleepTime) 267 | else: 268 | msg = f'{self._retries + 1} requests to {req.url} failed, giving up.' 269 | _logger.fatal(msg) 270 | _logger.fatal(f'Errors: {", ".join(errors)}') 271 | raise ScraperException(msg) 272 | raise RuntimeError('Reached unreachable code') 273 | 274 | def _get(self, *args, **kwargs): 275 | return self._request('GET', *args, **kwargs) 276 | 277 | def _post(self, *args, **kwargs): 278 | return self._request('POST', *args, **kwargs) 279 | 280 | @classmethod 281 | def _cli_setup_parser(cls, subparser): 282 | pass 283 | 284 | @classmethod 285 | def _cli_from_args(cls, args): 286 | return cls._cli_construct(args) 287 | 288 | @classmethod 289 | def _cli_construct(cls, argparseArgs, *args, **kwargs): 290 | return cls(*args, **kwargs, retries = argparseArgs.retries) 291 | 292 | 293 | __getattr__, __dir__ = snscrape.utils.module_deprecation_helper(__all__, Entity = Item) 294 | -------------------------------------------------------------------------------- /snscrape/modules/__init__.py: -------------------------------------------------------------------------------- 1 | import pkgutil 2 | 3 | 4 | __all__ = [] 5 | 6 | 7 | def _import_modules(): 8 | prefixLen = len(__name__) + 1 9 | for importer, moduleName, isPkg in pkgutil.iter_modules(__path__, prefix = f'{__name__}.'): 10 | assert not isPkg 11 | moduleNameWithoutPrefix = moduleName[prefixLen:] 12 | __all__.append(moduleNameWithoutPrefix) 13 | module = importer.find_module(moduleName).load_module(moduleName) 14 | globals()[moduleNameWithoutPrefix] = module 15 | 16 | 17 | _import_modules() 18 | -------------------------------------------------------------------------------- /snscrape/modules/facebook.py: -------------------------------------------------------------------------------- 1 | __all__ = ['FacebookPost', 'User', 'FacebookUserScraper', 'FacebookCommunityScraper', 'FacebookGroupScraper'] 2 | 3 | 4 | import bs4 5 | import dataclasses 6 | import datetime 7 | import json 8 | import logging 9 | import re 10 | import snscrape.base 11 | import snscrape.utils 12 | import typing 13 | import urllib.parse 14 | 15 | 16 | _logger = logging.getLogger(__name__) 17 | 18 | 19 | @dataclasses.dataclass 20 | class FacebookPost(snscrape.base.Item): 21 | cleanUrl: str 22 | dirtyUrl: str 23 | date: datetime.datetime 24 | content: typing.Optional[str] 25 | outlinks: list 26 | 27 | outlinksss = snscrape.base._DeprecatedProperty('outlinksss', lambda self: ' '.join(self.outlinks), 'outlinks') 28 | 29 | def __str__(self): 30 | return self.cleanUrl 31 | 32 | 33 | @dataclasses.dataclass 34 | class User(snscrape.base.Item): 35 | username: str 36 | pageId: int 37 | name: str 38 | verified: bool 39 | created: typing.Optional[datetime.date] = None 40 | pageOwner: typing.Optional[str] = None 41 | likes: typing.Optional[int] = None 42 | followers: typing.Optional[int] = None 43 | checkins: typing.Optional[int] = None 44 | address: typing.Optional[str] = None 45 | phone: typing.Optional[str] = None 46 | web: typing.Optional[str] = None 47 | keywords: typing.Optional[typing.List[str]] = None 48 | 49 | def __str__(self): 50 | return f'https://www.facebook.com/{self.username}/' 51 | 52 | 53 | class _FacebookCommonScraper(snscrape.base.Scraper): 54 | def _clean_url(self, dirtyUrl): 55 | u = urllib.parse.urlparse(dirtyUrl) 56 | if u.path == '/permalink.php': 57 | # Retain only story_fbid and id parameters 58 | q = urllib.parse.parse_qs(u.query) 59 | clean = (u.scheme, u.netloc, u.path, urllib.parse.urlencode((('story_fbid', q['story_fbid'][0]), ('id', q['id'][0]))), '') 60 | elif u.path == '/photo.php': 61 | # Retain only the fbid parameter 62 | q = urllib.parse.parse_qs(u.query) 63 | clean = (u.scheme, u.netloc, u.path, urllib.parse.urlencode((('fbid', q['fbid'][0]),)), '') 64 | elif u.path == '/media/set/': 65 | # Retain only the set parameter and try to shorten it to the minimum 66 | q = urllib.parse.parse_qs(u.query) 67 | setVal = q['set'][0] 68 | if setVal.rstrip('0123456789').endswith('.a.'): 69 | setVal = f'a.{setVal.rsplit(".", 1)[1]}' 70 | clean = (u.scheme, u.netloc, u.path, urllib.parse.urlencode((('set', setVal),)), '') 71 | elif u.path.split('/')[2] == 'posts' or u.path.startswith('/events/') or u.path.startswith('/notes/') or u.path.split('/')[1:4:2] == ['groups', 'permalink']: 72 | # No manipulation of the path needed, but strip the query string 73 | clean = (u.scheme, u.netloc, u.path, '', '') 74 | elif u.path.split('/')[2] in ('photos', 'videos'): 75 | # Path: "/" username or ID "/" photos or videos "/" crap "/" ID of photo or video "/" 76 | # But to be safe, also handle URLs that don't have that crap correctly. 77 | if u.path.count('/') == 4: 78 | clean = (u.scheme, u.netloc, u.path, '', '') 79 | elif u.path.count('/') == 5: 80 | # Strip out the third path component 81 | pathcomps = u.path.split('/') 82 | pathcomps.pop(3) # Don't forget about the empty string at the beginning! 83 | clean = (u.scheme, u.netloc, '/'.join(pathcomps), '', '') 84 | else: 85 | return dirtyUrl 86 | else: 87 | # If we don't recognise the URL, just return the original one. 88 | return dirtyUrl 89 | return urllib.parse.urlunsplit(clean) 90 | 91 | def _is_odd_link(self, href, entryText, mode): 92 | # Returns (isOddLink: bool, warn: bool|None) 93 | if mode == 'user': 94 | if not any(x in href for x in ('/posts/', '/photos/', '/videos/', '/permalink.php?', '/events/', '/notes/', '/photo.php?', '/media/set/')): 95 | if href == '#' and 'new photo' in entryText and 'to the album' in entryText: 96 | # Don't print a warning if it's a "User added 5 new photos to the album"-type entry, which doesn't have a permalink. 97 | return True, False 98 | elif href.startswith('/business/help/788160621327601/?'): 99 | # Skip the help article about branded content 100 | return True, False 101 | else: 102 | return True, True 103 | return False, None 104 | elif mode == 'group': 105 | if not re.match(r'^/groups/[^/]+/permalink/\d+/(\?|$)', href): 106 | return True, True 107 | return False, None 108 | 109 | def _soup_to_items(self, soup, baseUrl, mode): 110 | cleanUrl = None # Value from previous iteration is used for warning on link-less entries 111 | for entry in soup.find_all('div', class_ = '_5pcr'): # also class 'fbUserContent' in 2017 and 'userContentWrapper' in 2019 112 | # Check that this is not inside another div._5pcr to avoid duplicates or extracting the wrong URL (e.g. 'X was mentioned in a post' on community pages) 113 | parent = entry.parent 114 | isNested = False 115 | while parent: 116 | if parent.name == 'div' and 'class' in parent.attrs and '_5pcr' in parent.attrs['class']: 117 | isNested = True 118 | break 119 | parent = parent.parent 120 | if isNested: 121 | continue 122 | 123 | entryA = entry.find('a', class_ = '_5pcq') # There can be more than one, e.g. when a post is shared by another user, but the first one is always the one of this entry. 124 | mediaSetA = entry.find('a', class_ = '_17z-') 125 | if not mediaSetA and not entryA: 126 | _logger.warning(f'Ignoring link-less entry after {cleanUrl}: {entry.text!r}') 127 | continue 128 | if mediaSetA and (not entryA or entryA['href'] == '#'): 129 | href = mediaSetA['href'] 130 | elif entryA: 131 | href = entryA['href'] 132 | oddLink, warn = self._is_odd_link(href, entry.text, mode) 133 | if oddLink: 134 | if warn: 135 | _logger.warning(f'Ignoring odd link: {href}') 136 | continue 137 | dirtyUrl = urllib.parse.urljoin(baseUrl, href) 138 | cleanUrl = self._clean_url(dirtyUrl) 139 | date = datetime.datetime.fromtimestamp(int(entry.find('abbr', class_ = '_5ptz')['data-utime']), datetime.timezone.utc) 140 | if (contentDiv := entry.find('div', class_ = '_5pbx')): 141 | content = contentDiv.text 142 | else: 143 | content = None 144 | outlinks = [] 145 | for a in entry.find_all('a'): 146 | if not a.has_attr('href'): 147 | continue 148 | href = a.get('href') 149 | if not href.startswith('https://l.facebook.com/l.php?'): 150 | continue 151 | query = urllib.parse.parse_qs(urllib.parse.urlparse(href).query) 152 | if 'u' not in query or len(query['u']) != 1: 153 | _logger.warning(f'Ignoring odd outlink: {href}') 154 | continue 155 | outlink = query['u'][0] 156 | if outlink.startswith('http://') or outlink.startswith('https://') and outlink not in outlinks: 157 | outlinks.append(outlink) 158 | yield FacebookPost(cleanUrl = cleanUrl, dirtyUrl = dirtyUrl, date = date, content = content, outlinks = outlinks) 159 | 160 | 161 | class _FacebookUserAndCommunityScraper(_FacebookCommonScraper): 162 | def __init__(self, username, **kwargs): 163 | super().__init__(**kwargs) 164 | self._username = username 165 | self._headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i686; rv:78.0) Gecko/20100101 Firefox/78.0', 'Accept-Language': 'en-US,en;q=0.5'} 166 | self._initialPage = None 167 | self._initialPageSoup = None 168 | 169 | def _initial_page(self): 170 | if self._initialPage is None: 171 | _logger.info('Retrieving initial data') 172 | r = self._get(self._baseUrl, headers = self._headers) 173 | if r.status_code not in (200, 404): 174 | raise snscrape.base.ScraperException(f'Got status code {r.status_code}') 175 | self._initialPage = r 176 | self._initialPageSoup = bs4.BeautifulSoup(r.text, 'lxml') 177 | return self._initialPage, self._initialPageSoup 178 | 179 | def get_items(self): 180 | nextPageLinkPattern = re.compile(r'^/pages_reaction_units/more/\?page_id=') 181 | spuriousForLoopPattern = re.compile(r'^for \(;;\);') 182 | 183 | r, soup = self._initial_page() 184 | if r.status_code == 404: 185 | _logger.warning('User does not exist') 186 | return 187 | yield from self._soup_to_items(soup, self._baseUrl, 'user') 188 | 189 | while (nextPageLink := soup.find('a', ajaxify = nextPageLinkPattern)): 190 | _logger.info('Retrieving next page') 191 | 192 | # The web app sends a bunch of additional parameters. Most of them would be easy to add, but there's also __dyn, which is a compressed list of the "modules" loaded in the browser. 193 | # Reproducing that would be difficult to get right, especially as Facebook's codebase evolves, so it's just not sent at all here. 194 | r = self._get(urllib.parse.urljoin(self._baseUrl, nextPageLink.get('ajaxify')) + '&__a=1', headers = self._headers) 195 | if r.status_code != 200: 196 | raise snscrape.base.ScraperException(f'Got status code {r.status_code}') 197 | response = json.loads(spuriousForLoopPattern.sub('', r.text)) 198 | assert 'domops' in response 199 | assert len(response['domops']) == 1 200 | assert len(response['domops'][0]) == 4 201 | assert response['domops'][0][0] == 'replace', f'{response["domops"][0]} is not "replace"' 202 | assert response['domops'][0][1] in ('#www_pages_reaction_see_more_unitwww_pages_home', '#www_pages_reaction_see_more_unitwww_pages_community_tab') 203 | assert response['domops'][0][2] == False 204 | assert '__html' in response['domops'][0][3] 205 | soup = bs4.BeautifulSoup(response['domops'][0][3]['__html'], 'lxml') 206 | yield from self._soup_to_items(soup, self._baseUrl, 'user') 207 | 208 | @classmethod 209 | def _cli_setup_parser(cls, subparser): 210 | subparser.add_argument('username', type = snscrape.utils.nonempty_string_arg('username'), help = 'A Facebook username or user ID') 211 | 212 | @classmethod 213 | def _cli_from_args(cls, args): 214 | return cls._cli_construct(args, args.username) 215 | 216 | 217 | class FacebookUserScraper(_FacebookUserAndCommunityScraper): 218 | name = 'facebook-user' 219 | 220 | def __init__(self, *args, **kwargs): 221 | super().__init__(*args, **kwargs) 222 | self._baseUrl = f'https://www.facebook.com/{self._username}/' 223 | 224 | def _get_entity(self): 225 | kwargs = {} 226 | 227 | nameVerifiedMarkupPattern = re.compile(r'"markup":\[\["__markup_a588f507_0_0",\{"__html":(".*?")\}') 228 | handleDivPattern = re.compile(r']*(?<=\s)data-key\s*=\s*"tab_home".*?') 229 | handlePattern = re.compile(r']*(?<=\s)href="/([^/]+)') 230 | months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] 231 | createdDatePattern = re.compile('^(' + '|'.join(months) + r') (\d+), (\d+)$') 232 | 233 | r, soup = self._initial_page() 234 | if r.status_code != 200: 235 | return 236 | 237 | handleDiv = handleDivPattern.search(r.text) 238 | handle = handlePattern.search(handleDiv.group(0)) 239 | kwargs['username'] = handle.group(1) 240 | 241 | nameVerifiedMarkup = nameVerifiedMarkupPattern.search(r.text) 242 | nameVerifiedMarkup = json.loads(nameVerifiedMarkup.group(1)) 243 | nameVerifiedSoup = bs4.BeautifulSoup(nameVerifiedMarkup, 'lxml') 244 | kwargs['name'] = nameVerifiedSoup.find('a', class_ = '_64-f').text 245 | kwargs['verified'] = bool(nameVerifiedSoup.find('a', class_ = '_56_f')) 246 | 247 | pageTransparencyContentDiv = soup.find('div', class_ = '_61-0') 248 | if pageTransparencyContentDiv.text.startswith('Page created - '): 249 | createdDateMess = pageTransparencyContentDiv.text.split(' - ', 1)[1] 250 | m = createdDatePattern.match(createdDateMess) 251 | assert m, 'unexpected created div content' 252 | kwargs['created'] = datetime.date(int(m.group(3)), months.index(m.group(1)) + 1, int(m.group(2))) 253 | if pageTransparencyContentDiv.text.startswith('Confirmed Page Owner: '): 254 | kwargs['pageOwner'] = pageTransparencyContentDiv.text.split(': ', 1)[1] 255 | 256 | communityDiv = soup.find('div', class_ = '_6590') 257 | for div in communityDiv.find_all('div', class_ = '_4bl9'): 258 | text = div.text 259 | if text.endswith(' people like this'): 260 | kwargs['likes'] = int(text.split(' ', 1)[0].replace(',', '')) 261 | elif text.endswith(' people follow this'): 262 | kwargs['followers'] = int(text.split(' ', 1)[0].replace(',', '')) 263 | elif text.endswith(' check-ins'): 264 | kwargs['checkins'] = int(text.split(' ', 1)[0].replace(',', '')) 265 | 266 | aboutDiv = soup.find('div', class_ = '_u9q') 267 | if aboutDiv: 268 | # As if the above wasn't already ugly enough, this is where it gets really bad... 269 | for div in aboutDiv.find_all('div', class_ = '_2pi9'): 270 | img = div.find('img', class_ = '_3-91') 271 | if not img: 272 | continue 273 | if img['src'] == 'https://static.xx.fbcdn.net/rsrc.php/v3/y5/r/vfXKA62x4Da.png': # Address 274 | rawAddress = div.find('div', class_ = '_2wzd').text 275 | kwargs['address'] = re.sub(r' \((\d+,)?\d+(\.\d+)? mi\)', '\n', rawAddress) # Remove distance from inferred IP location, restore linebreak 276 | elif img['src'] == 'https://static.xx.fbcdn.net/rsrc.php/v3/yW/r/mYv88EsODOI.png': # Phone number 277 | kwargs['phone'] = div.find('div', class_ = '_4bl9').text 278 | elif img['src'] == 'https://static.xx.fbcdn.net/rsrc.php/v3/yx/r/xVA3lB-GVep.png': # Web link 279 | for a in div.find_all('a'): 280 | if a.text == '' or 'href' not in a.attrs or a.find('span'): 281 | continue 282 | dirtyWeb = a['href'] 283 | assert dirtyWeb.startswith('https://l.facebook.com/l.php?u='), 'unexpected web link' 284 | kwargs['web'] = urllib.parse.unquote(dirtyWeb.split('=', 1)[1].split('&', 1)[0]) 285 | elif img['src'] == 'https://static.xx.fbcdn.net/rsrc.php/v3/yl/r/LwDWwC1d0Rx.png': # Keywords 286 | kwargs['keywords'] = div.find('div', class_ = '_4bl9').text.split(' · ') 287 | 288 | androidUrlMeta = soup.find('meta', property = 'al:android:url') 289 | assert androidUrlMeta['content'].startswith('fb://page/') and androidUrlMeta['content'].endswith('?referrer=app_link') 290 | kwargs['pageId'] = int(androidUrlMeta['content'][10:-18]) 291 | 292 | return User(**kwargs) 293 | 294 | 295 | class FacebookCommunityScraper(_FacebookUserAndCommunityScraper): 296 | name = 'facebook-community' 297 | 298 | def __init__(self, *args, **kwargs): 299 | super().__init__(*args, **kwargs) 300 | self._baseUrl = f'https://www.facebook.com/{self._username}/community/' 301 | 302 | 303 | class FacebookGroupScraper(_FacebookCommonScraper): 304 | name = 'facebook-group' 305 | 306 | def __init__(self, group, **kwargs): 307 | super().__init__(**kwargs) 308 | self._group = group 309 | 310 | def get_items(self): 311 | headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Accept-Language': 'en-US,en;q=0.5'} 312 | 313 | pageletDataPattern = re.compile(r'"GroupEntstreamPagelet",\{.*?\}(?=,\{)') 314 | pageletDataPrefixLength = len('"GroupEntstreamPagelet",') 315 | spuriousForLoopPattern = re.compile(r'^for \(;;\);') 316 | 317 | baseUrl = f'https://upload.facebook.com/groups/{self._group}/?sorting_setting=CHRONOLOGICAL' 318 | r = self._get(baseUrl, headers = headers) 319 | if r.status_code == 404: 320 | _logger.warning('Group does not exist') 321 | return 322 | elif r.status_code != 200: 323 | raise snscrape.base.ScraperException(f'Got status code {r.status_code}') 324 | 325 | if 'content:{pagelet_group_mall:{container_id:"' not in r.text: 326 | raise snscrape.base.ScraperException('Code container ID marker not found (does the group exist?)') 327 | 328 | soup = bs4.BeautifulSoup(r.text, 'lxml') 329 | 330 | # Posts are inside an HTML comment in two code tags with IDs listed in JS... 331 | for codeContainerIdStart in ('content:{pagelet_group_mall:{container_id:"', 'content:{group_mall_after_tti:{container_id:"'): 332 | codeContainerIdPos = r.text.index(codeContainerIdStart) + len(codeContainerIdStart) 333 | codeContainerId = r.text[codeContainerIdPos : r.text.index('"', codeContainerIdPos)] 334 | codeContainer = soup.find('code', id = codeContainerId) 335 | if not codeContainer: 336 | raise snscrape.base.ScraperException('Code container not found') 337 | if type(codeContainer.string) is not bs4.element.Comment: 338 | raise snscrape.base.ScraperException('Code container does not contain a comment') 339 | codeSoup = bs4.BeautifulSoup(codeContainer.string, 'lxml') 340 | yield from self._soup_to_items(codeSoup, baseUrl, 'group') 341 | 342 | # Pagination 343 | while (data := pageletDataPattern.search(r.text).group(0)[pageletDataPrefixLength:]): 344 | # As on the user profile pages, the web app sends a lot of additional parameters, but those all seem to be unnecessary (although some change the response format, e.g. from JSON to HTML) 345 | r = self._get( 346 | 'https://upload.facebook.com/ajax/pagelet/generic.php/GroupEntstreamPagelet', 347 | params = {'data': data, '__a': 1}, 348 | headers = headers, 349 | ) 350 | if r.status_code != 200: 351 | raise snscrape.base.ScraperException(f'Got status code {r.status_code}') 352 | obj = json.loads(spuriousForLoopPattern.sub('', r.text)) 353 | if obj['payload'] == '': 354 | # End of pagination 355 | break 356 | soup = bs4.BeautifulSoup(obj['payload'], 'lxml') 357 | yield from self._soup_to_items(soup, baseUrl, 'group') 358 | 359 | @classmethod 360 | def _cli_setup_parser(cls, subparser): 361 | subparser.add_argument('group', type = snscrape.utils.nonempty_string_arg('group'), help = 'A group name or ID') 362 | 363 | @classmethod 364 | def _cli_from_args(cls, args): 365 | return cls._cli_construct(args, args.group) 366 | -------------------------------------------------------------------------------- /snscrape/modules/instagram.py: -------------------------------------------------------------------------------- 1 | __all__ = ['InstagramPost', 'User', 'InstagramUserScraper', 'InstagramHashtagScraper', 'InstagramLocationScraper'] 2 | 3 | 4 | import dataclasses 5 | import datetime 6 | import hashlib 7 | import json 8 | import logging 9 | import re 10 | import snscrape.base 11 | import snscrape.utils 12 | import typing 13 | 14 | 15 | _logger = logging.getLogger(__name__) 16 | 17 | 18 | @dataclasses.dataclass 19 | class InstagramPost(snscrape.base.Item): 20 | url: str 21 | date: datetime.datetime 22 | content: typing.Optional[str] 23 | thumbnailUrl: str 24 | displayUrl: str 25 | username: typing.Optional[str] 26 | likes: int 27 | comments: int 28 | commentsDisabled: bool 29 | isVideo: bool 30 | 31 | def __str__(self): 32 | return self.url 33 | 34 | 35 | @dataclasses.dataclass 36 | class User(snscrape.base.Item): 37 | username: str 38 | name: typing.Optional[str] 39 | followers: snscrape.base.IntWithGranularity 40 | following: snscrape.base.IntWithGranularity 41 | posts: snscrape.base.IntWithGranularity 42 | 43 | followersGranularity = snscrape.base._DeprecatedProperty('followersGranularity', lambda self: self.followers.granularity, 'followers.granularity') 44 | followingGranularity = snscrape.base._DeprecatedProperty('followingGranularity', lambda self: self.following.granularity, 'following.granularity') 45 | postsGranularity = snscrape.base._DeprecatedProperty('postsGranularity', lambda self: self.posts.granularity, 'posts.granularity') 46 | 47 | def __str__(self): 48 | return f'https://www.instagram.com/{self.username}/' 49 | 50 | 51 | class _InstagramCommonScraper(snscrape.base.Scraper): 52 | def __init__(self, **kwargs): 53 | super().__init__(**kwargs) 54 | self._headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} 55 | self._initialPage = None 56 | 57 | def _response_to_items(self, response): 58 | for node in response[self._responseContainer][self._edgeXToMedia]['edges']: 59 | code = node['node']['shortcode'] 60 | username = node['node']['owner']['username'] if 'username' in node['node']['owner'] else None 61 | url = f'https://www.instagram.com/p/{code}/' 62 | yield InstagramPost( 63 | url = url, 64 | date = datetime.datetime.fromtimestamp(node['node']['taken_at_timestamp'], datetime.timezone.utc), 65 | content = node['node']['edge_media_to_caption']['edges'][0]['node']['text'] if len(node['node']['edge_media_to_caption']['edges']) else None, 66 | thumbnailUrl = node['node']['thumbnail_src'], 67 | displayUrl = node['node']['display_url'], 68 | username = username, 69 | likes = node['node']['edge_media_preview_like']['count'], 70 | comments = node['node']['edge_media_to_comment']['count'], 71 | commentsDisabled = node['node']['comments_disabled'], 72 | isVideo = node['node']['is_video'], 73 | ) 74 | 75 | def _initial_page(self): 76 | if self._initialPage is None: 77 | _logger.info('Retrieving initial data') 78 | r = self._get(self._initialUrl, headers = self._headers, responseOkCallback = self._check_initial_page_callback) 79 | if r.status_code not in (200, 404): 80 | raise snscrape.base.ScraperException(f'Got status code {r.status_code}') 81 | elif r.url.startswith('https://www.instagram.com/accounts/login/'): 82 | raise snscrape.base.ScraperException('Redirected to login page') 83 | self._initialPage = r 84 | return self._initialPage 85 | 86 | def _check_initial_page_callback(self, r): 87 | if r.status_code != 200: 88 | return True, None 89 | jsonData = r.text.split('')[0] # May throw an IndexError if Instagram changes something again; we just let that bubble. 90 | try: 91 | obj = json.loads(jsonData) 92 | except json.JSONDecodeError: 93 | return False, 'invalid JSON' 94 | r._snscrape_json_obj = obj 95 | return True, None 96 | 97 | def _check_json_callback(self, r): 98 | if r.status_code != 200: 99 | return False, f'status code {r.status_code}' 100 | if r.url.startswith('https://www.instagram.com/accounts/login/'): 101 | raise snscrape.base.ScraperException('Redirected to login page') 102 | try: 103 | obj = json.loads(r.text) 104 | except json.JSONDecodeError as e: 105 | return False, f'invalid JSON ({e!r})' 106 | r._snscrape_json_obj = obj 107 | return True, None 108 | 109 | def get_items(self): 110 | r = self._initial_page() 111 | if r.status_code == 404: 112 | _logger.warning('Page does not exist') 113 | return 114 | response = r._snscrape_json_obj 115 | rhxGis = response['rhx_gis'] if 'rhx_gis' in response else '' 116 | if response['entry_data'][self._pageName][0]['graphql'][self._responseContainer][self._edgeXToMedia]['count'] == 0: 117 | _logger.info('Page has no posts') 118 | return 119 | if not response['entry_data'][self._pageName][0]['graphql'][self._responseContainer][self._edgeXToMedia]['edges']: 120 | _logger.warning('Private account') 121 | return 122 | pageID = response['entry_data'][self._pageName][0]['graphql'][self._responseContainer][self._pageIDKey] 123 | yield from self._response_to_items(response['entry_data'][self._pageName][0]['graphql']) 124 | if not response['entry_data'][self._pageName][0]['graphql'][self._responseContainer][self._edgeXToMedia]['page_info']['has_next_page']: 125 | return 126 | endCursor = response['entry_data'][self._pageName][0]['graphql'][self._responseContainer][self._edgeXToMedia]['page_info']['end_cursor'] 127 | 128 | headers = self._headers.copy() 129 | while True: 130 | _logger.info(f'Retrieving endCursor = {endCursor!r}') 131 | variables = self._variablesFormat.format(**locals()) 132 | headers['X-Requested-With'] = 'XMLHttpRequest' 133 | headers['X-Instagram-GIS'] = hashlib.md5(f'{rhxGis}:{variables}'.encode('utf-8')).hexdigest() 134 | r = self._get(f'https://www.instagram.com/graphql/query/?query_hash={self._queryHash}&variables={variables}', headers = headers, responseOkCallback = self._check_json_callback) 135 | 136 | if r.status_code != 200: 137 | raise snscrape.base.ScraperException(f'Got status code {r.status_code}') 138 | 139 | response = r._snscrape_json_obj 140 | if not response['data'][self._responseContainer][self._edgeXToMedia]['edges']: 141 | return 142 | yield from self._response_to_items(response['data']) 143 | if not response['data'][self._responseContainer][self._edgeXToMedia]['page_info']['has_next_page']: 144 | return 145 | endCursor = response['data'][self._responseContainer][self._edgeXToMedia]['page_info']['end_cursor'] 146 | 147 | 148 | class InstagramUserScraper(_InstagramCommonScraper): 149 | name = 'instagram-user' 150 | 151 | def __init__(self, username, **kwargs): 152 | super().__init__(**kwargs) 153 | self._initialUrl = f'https://www.instagram.com/{username}/' 154 | self._pageName = 'ProfilePage' 155 | self._responseContainer = 'user' 156 | self._edgeXToMedia = 'edge_owner_to_timeline_media' 157 | self._pageIDKey = 'id' 158 | self._queryHash = 'f2405b236d85e8296cf30347c9f08c2a' 159 | self._variablesFormat = '{{"id":"{pageID}","first":50,"after":"{endCursor}"}}' 160 | 161 | def _get_entity(self): 162 | r = self._initial_page() 163 | if r.status_code != 200: 164 | return 165 | if ' len(id2): 71 | return 1 72 | if id1 < id2: 73 | return -1 74 | if id1 > id2: 75 | return 1 76 | return 0 77 | 78 | 79 | class _RedditPushshiftScraper(snscrape.base.Scraper): 80 | def __init__(self, **kwargs): 81 | super().__init__(**kwargs) 82 | self._headers = {'User-Agent': f'snscrape/{snscrape.version.__version__}'} 83 | 84 | def _handle_rate_limiting(self, r): 85 | if r.status_code == 429: 86 | _logger.info('Got 429 response, sleeping') 87 | time.sleep(10) 88 | return False, 'rate-limited' 89 | if r.status_code != 200: 90 | return False, 'non-200 status code' 91 | return True, None 92 | 93 | def _get_api(self, url, params = None): 94 | r = self._get(url, params = params, headers = self._headers, responseOkCallback = self._handle_rate_limiting) 95 | if r.status_code != 200: 96 | raise snscrape.base.ScraperException(f'Got status code {r.status_code}') 97 | return r.json() 98 | 99 | def _api_obj_to_item(self, d): 100 | cls = Submission if 'title' in d else Comment 101 | 102 | # Pushshift doesn't always return a permalink; sometimes, there's a permalink_url instead, and sometimes there's nothing at all 103 | permalink = d.get('permalink') 104 | if permalink is None: 105 | # E.g. comment dovj2v7 106 | permalink = d.get('permalink_url') 107 | if permalink is None: 108 | if 'link_id' in d and d['link_id'].startswith('t3_'): # E.g. comment doraazf 109 | if 'subreddit' in d: 110 | permalink = f'/r/{d["subreddit"]}/comments/{d["link_id"][3:]}/_/{d["id"]}/' 111 | else: # E.g. submission 617p51 but can likely happen for comments as well 112 | permalink = f'/comments/{d["link_id"][3:]}/_/{d["id"]}/' 113 | else: 114 | _logger.warning('Unable to find or construct permalink') 115 | permalink = '/' 116 | 117 | kwargs = { 118 | 'author': d.get('author'), 119 | 'date': datetime.datetime.fromtimestamp(d['created_utc'], datetime.timezone.utc), 120 | 'url': f'https://old.reddit.com{permalink}', 121 | 'subreddit': d.get('subreddit'), 122 | } 123 | if cls is Submission: 124 | kwargs['selftext'] = d.get('selftext') or None 125 | kwargs['link'] = (d['url'] if not d['url'].startswith('/') else f'https://old.reddit.com{d["url"]}') if not kwargs['selftext'] else None 126 | if kwargs['link'] == kwargs['url'] or kwargs['url'].replace('//old.reddit.com/', '//www.reddit.com/') == kwargs['link']: 127 | kwargs['link'] = None 128 | kwargs['title'] = d['title'] 129 | kwargs['id'] = f't3_{d["id"]}' 130 | else: 131 | kwargs['body'] = d['body'] 132 | kwargs['parentId'] = d.get('parent_id') 133 | kwargs['id'] = f't1_{d["id"]}' 134 | 135 | return cls(**kwargs) 136 | 137 | def _iter_api(self, url, params = None): 138 | '''Iterate through the Pushshift API using the 'until' parameter and yield the items.''' 139 | lowestIdSeen = None 140 | if params is None: 141 | params = {} 142 | while True: 143 | obj = self._get_api(url, params = params) 144 | if not obj['data'] or (lowestIdSeen is not None and all(_cmp_id(d['id'], lowestIdSeen) >= 0 for d in obj['data'])): # end of pagination 145 | break 146 | for d in obj['data']: 147 | if lowestIdSeen is None or _cmp_id(d['id'], lowestIdSeen) == -1: 148 | yield self._api_obj_to_item(d) 149 | lowestIdSeen = d['id'] 150 | params['until'] = obj["data"][-1]["created_utc"] + 1 151 | 152 | 153 | class _RedditPushshiftSearchScraper(_RedditPushshiftScraper): 154 | def __init__(self, name, *, submissions = True, comments = True, before = None, after = None, **kwargs): 155 | super().__init__(**kwargs) 156 | self._name = name 157 | self._submissions = submissions 158 | self._comments = comments 159 | self._before = before 160 | self._after = after 161 | 162 | if not type(self)._validationFunc(self._name): 163 | raise ValueError(f'invalid {type(self).name.split("-", 1)[1]} name') 164 | if not self._submissions and not self._comments: 165 | raise ValueError('At least one of submissions and comments must be True') 166 | 167 | def _iter_api_submissions_and_comments(self, params: dict): 168 | # Retrieve both submissions and comments, interleave the results to get a reverse-chronological order 169 | params['limit'] = '1000' 170 | if self._before is not None: 171 | params['until'] = self._before 172 | if self._after is not None: 173 | params['since'] = self._after 174 | 175 | if self._submissions: 176 | submissionsIter = self._iter_api('https://api.pushshift.io/reddit/search/submission', params.copy()) # Pass copies to prevent the two iterators from messing each other up by using the same dict 177 | else: 178 | submissionsIter = iter(()) 179 | if self._comments: 180 | commentsIter = self._iter_api('https://api.pushshift.io/reddit/search/comment', params.copy()) 181 | else: 182 | commentsIter = iter(()) 183 | 184 | try: 185 | tipSubmission = next(submissionsIter) 186 | except StopIteration: 187 | # There are no submissions, just yield comments and return 188 | yield from commentsIter 189 | return 190 | try: 191 | tipComment = next(commentsIter) 192 | except StopIteration: 193 | # There are no comments, just yield submissions and return 194 | yield tipSubmission 195 | yield from submissionsIter 196 | return 197 | 198 | while True: 199 | # Return newer first; if both have the same creation datetime, return the comment first 200 | if tipSubmission.date > tipComment.date: 201 | yield tipSubmission 202 | try: 203 | tipSubmission = next(submissionsIter) 204 | except StopIteration: 205 | # Reached the end of submissions, just yield the remaining comments and stop 206 | yield tipComment 207 | yield from commentsIter 208 | break 209 | else: 210 | yield tipComment 211 | try: 212 | tipComment = next(commentsIter) 213 | except StopIteration: 214 | yield tipSubmission 215 | yield from submissionsIter 216 | break 217 | 218 | def get_items(self): 219 | yield from self._iter_api_submissions_and_comments({type(self)._apiField: self._name}) 220 | 221 | @classmethod 222 | def _cli_setup_parser(cls, subparser): 223 | subparser.add_argument('--no-submissions', dest = 'noSubmissions', action = 'store_true', default = False, help = 'Don\'t list submissions') 224 | subparser.add_argument('--no-comments', dest = 'noComments', action = 'store_true', default = False, help = 'Don\'t list comments') 225 | subparser.add_argument('--before', metavar = 'TIMESTAMP', type = int, help = 'Fetch results before a Unix timestamp') 226 | subparser.add_argument('--after', metavar = 'TIMESTAMP', type = int, help = 'Fetch results after a Unix timestamp') 227 | name = cls.name.split('-', 1)[1] 228 | subparser.add_argument(name, type = snscrape.utils.nonempty_string_arg(name)) 229 | 230 | @classmethod 231 | def _cli_from_args(cls, args): 232 | name = cls.name.split('-', 1)[1] 233 | return cls._cli_construct(args, getattr(args, name), submissions = not args.noSubmissions, comments = not args.noComments, before = args.before, after = args.after) 234 | 235 | 236 | class RedditUserScraper(_RedditPushshiftSearchScraper): 237 | name = 'reddit-user' 238 | _validationFunc = lambda x: re.match('^[A-Za-z0-9_-]{3,20}$', x) 239 | _apiField = 'author' 240 | 241 | 242 | class RedditSubredditScraper(_RedditPushshiftSearchScraper): 243 | name = 'reddit-subreddit' 244 | _validationFunc = lambda x: re.match('^[A-Za-z0-9][A-Za-z0-9_]{2,20}$', x) 245 | _apiField = 'subreddit' 246 | 247 | 248 | class RedditSearchScraper(_RedditPushshiftSearchScraper): 249 | name = 'reddit-search' 250 | _validationFunc = lambda x: True 251 | _apiField = 'q' 252 | 253 | 254 | class RedditSubmissionScraper(_RedditPushshiftScraper): 255 | name = 'reddit-submission' 256 | 257 | def __init__(self, submissionId, **kwargs): 258 | if (submissionId[3:] if submissionId.startswith('t3_') else submissionId).strip(string.ascii_lowercase + string.digits) != '': 259 | raise ValueError('invalid submissionId') 260 | super().__init__(**kwargs) 261 | self._submissionId = submissionId 262 | 263 | def get_items(self): 264 | obj = self._get_api(f'https://api.pushshift.io/reddit/search/submission?ids={self._submissionId}') 265 | if not obj['data']: 266 | return 267 | if len(obj['data']) != 1: 268 | raise snscrape.base.ScraperException(f'Got {len(obj["data"])} results instead of 1') 269 | yield self._api_obj_to_item(obj['data'][0]) 270 | 271 | # Upstream bug: link_id must be provided in decimal https://old.reddit.com/r/pushshift/comments/zkggt0/update_on_colo_switchover_bug_fixes_reindexing/ 272 | yield from self._iter_api('https://api.pushshift.io/reddit/search/comment', {'link_id': int(self._submissionId, 36), 'limit': 1000}) 273 | 274 | @classmethod 275 | def _cli_setup_parser(cls, subparser): 276 | subparser.add_argument('submissionId', type = snscrape.utils.nonempty_string_arg('submissionId')) 277 | 278 | @classmethod 279 | def _cli_from_args(cls, args): 280 | return cls._cli_construct(args, args.submissionId) 281 | -------------------------------------------------------------------------------- /snscrape/modules/telegram.py: -------------------------------------------------------------------------------- 1 | __all__ = ['LinkPreview', 'TelegramPost', 'Channel', 'TelegramChannelScraper'] 2 | 3 | 4 | import bs4 5 | import dataclasses 6 | import datetime 7 | import logging 8 | import re 9 | import snscrape.base 10 | import snscrape.utils 11 | import typing 12 | import urllib.parse 13 | 14 | 15 | _logger = logging.getLogger(__name__) 16 | _SINGLE_MEDIA_LINK_PATTERN = re.compile(r'^https://t\.me/[^/]+/\d+\?single$') 17 | 18 | 19 | @dataclasses.dataclass 20 | class LinkPreview: 21 | href: str 22 | siteName: typing.Optional[str] = None 23 | title: typing.Optional[str] = None 24 | description: typing.Optional[str] = None 25 | image: typing.Optional[str] = None 26 | 27 | 28 | @dataclasses.dataclass 29 | class TelegramPost(snscrape.base.Item): 30 | url: str 31 | date: datetime.datetime 32 | content: str 33 | outlinks: list 34 | linkPreview: typing.Optional[LinkPreview] = None 35 | 36 | outlinksss = snscrape.base._DeprecatedProperty('outlinksss', lambda self: ' '.join(self.outlinks), 'outlinks') 37 | 38 | def __str__(self): 39 | return self.url 40 | 41 | 42 | @dataclasses.dataclass 43 | class Channel(snscrape.base.Item): 44 | username: str 45 | title: str 46 | verified: bool 47 | photo: str 48 | description: typing.Optional[str] = None 49 | members: typing.Optional[int] = None 50 | photos: typing.Optional[snscrape.base.IntWithGranularity] = None 51 | videos: typing.Optional[snscrape.base.IntWithGranularity] = None 52 | links: typing.Optional[snscrape.base.IntWithGranularity] = None 53 | files: typing.Optional[snscrape.base.IntWithGranularity] = None 54 | 55 | photosGranularity = snscrape.base._DeprecatedProperty('photosGranularity', lambda self: self.photos.granularity, 'photos.granularity') 56 | videosGranularity = snscrape.base._DeprecatedProperty('videosGranularity', lambda self: self.videos.granularity, 'videos.granularity') 57 | linksGranularity = snscrape.base._DeprecatedProperty('linksGranularity', lambda self: self.links.granularity, 'links.granularity') 58 | filesGranularity = snscrape.base._DeprecatedProperty('filesGranularity', lambda self: self.files.granularity, 'files.granularity') 59 | 60 | def __str__(self): 61 | return f'https://t.me/s/{self.username}' 62 | 63 | 64 | class TelegramChannelScraper(snscrape.base.Scraper): 65 | name = 'telegram-channel' 66 | 67 | def __init__(self, name, **kwargs): 68 | super().__init__(**kwargs) 69 | self._name = name 70 | self._headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'} 71 | self._initialPage = None 72 | self._initialPageSoup = None 73 | 74 | def _initial_page(self): 75 | if self._initialPage is None: 76 | r = self._get(f'https://t.me/s/{self._name}', headers = self._headers) 77 | if r.status_code != 200: 78 | raise snscrape.base.ScraperException(f'Got status code {r.status_code}') 79 | self._initialPage, self._initialPageSoup = r, bs4.BeautifulSoup(r.text, 'lxml') 80 | return self._initialPage, self._initialPageSoup 81 | 82 | def _soup_to_items(self, soup, pageUrl, onlyUsername = False): 83 | posts = soup.find_all('div', attrs = {'class': 'tgme_widget_message', 'data-post': True}) 84 | for post in reversed(posts): 85 | if onlyUsername: 86 | yield post['data-post'].split('/')[0] 87 | return 88 | dateDiv = post.find('div', class_ = 'tgme_widget_message_footer').find('a', class_ = 'tgme_widget_message_date') 89 | rawUrl = dateDiv['href'] 90 | if not rawUrl.startswith('https://t.me/') or sum(x == '/' for x in rawUrl) != 4 or rawUrl.rsplit('/', 1)[1].strip('0123456789') != '': 91 | _logger.warning(f'Possibly incorrect URL: {rawUrl!r}') 92 | url = rawUrl.replace('//t.me/', '//t.me/s/') 93 | date = datetime.datetime.strptime(dateDiv.find('time', datetime = True)['datetime'].replace('-', '', 2).replace(':', ''), '%Y%m%dT%H%M%S%z') 94 | if (message := post.find('div', class_ = 'tgme_widget_message_text')): 95 | content = message.text 96 | outlinks = [] 97 | for link in post.find_all('a'): 98 | if any(x in link.parent.attrs.get('class', []) for x in ('tgme_widget_message_user', 'tgme_widget_message_author')): 99 | # Author links at the top (avatar and name) 100 | continue 101 | if link['href'] == rawUrl or link['href'] == url: 102 | # Generic filter of links to the post itself, catches videos, photos, and the date link 103 | continue 104 | if _SINGLE_MEDIA_LINK_PATTERN.match(link['href']): 105 | # Individual photo or video link 106 | continue 107 | href = urllib.parse.urljoin(pageUrl, link['href']) 108 | if href not in outlinks: 109 | outlinks.append(href) 110 | else: 111 | content = None 112 | outlinks = [] 113 | linkPreview = None 114 | if (linkPreviewA := post.find('a', class_ = 'tgme_widget_message_link_preview')): 115 | kwargs = {} 116 | kwargs['href'] = urllib.parse.urljoin(pageUrl, linkPreviewA['href']) 117 | if (siteNameDiv := linkPreviewA.find('div', class_ = 'link_preview_site_name')): 118 | kwargs['siteName'] = siteNameDiv.text 119 | if (titleDiv := linkPreviewA.find('div', class_ = 'link_preview_title')): 120 | kwargs['title'] = titleDiv.text 121 | if (descriptionDiv := linkPreviewA.find('div', class_ = 'link_preview_description')): 122 | kwargs['description'] = descriptionDiv.text 123 | if (imageI := linkPreviewA.find('i', class_ = 'link_preview_image')): 124 | if imageI['style'].startswith("background-image:url('"): 125 | kwargs['image'] = imageI['style'][22 : imageI['style'].index("'", 22)] 126 | else: 127 | _logger.warning(f'Could not process link preview image on {url}') 128 | linkPreview = LinkPreview(**kwargs) 129 | yield TelegramPost(url = url, date = date, content = content, outlinks = outlinks, linkPreview = linkPreview) 130 | 131 | def get_items(self): 132 | r, soup = self._initial_page() 133 | if '/s/' not in r.url: 134 | _logger.warning('No public post list for this user') 135 | return 136 | while True: 137 | yield from self._soup_to_items(soup, r.url) 138 | pageLink = soup.find('a', attrs = {'class': 'tme_messages_more', 'data-before': True}) 139 | if not pageLink: 140 | break 141 | nextPageUrl = urllib.parse.urljoin(r.url, pageLink['href']) 142 | r = self._get(nextPageUrl, headers = self._headers) 143 | if r.status_code != 200: 144 | raise snscrape.base.ScraperException(f'Got status code {r.status_code}') 145 | soup = bs4.BeautifulSoup(r.text, 'lxml') 146 | 147 | def _get_entity(self): 148 | kwargs = {} 149 | # /channel has a more accurate member count and bigger profile picture 150 | r = self._get(f'https://t.me/{self._name}', headers = self._headers) 151 | if r.status_code != 200: 152 | raise snscrape.base.ScraperException(f'Got status code {r.status_code}') 153 | soup = bs4.BeautifulSoup(r.text, 'lxml') 154 | membersDiv = soup.find('div', class_ = 'tgme_page_extra') 155 | if membersDiv.text.endswith(' subscribers'): 156 | kwargs['members'] = int(membersDiv.text[:-12].replace(' ', '')) 157 | kwargs['photo'] = soup.find('img', class_ = 'tgme_page_photo_image').attrs['src'] 158 | 159 | r, soup = self._initial_page() 160 | if '/s/' not in r.url: # Redirect on channels without public posts 161 | return 162 | channelInfoDiv = soup.find('div', class_ = 'tgme_channel_info') 163 | assert channelInfoDiv, 'channel info div not found' 164 | titleDiv = channelInfoDiv.find('div', class_ = 'tgme_channel_info_header_title') 165 | kwargs['title'] = titleDiv.find('span').text 166 | kwargs['verified'] = bool(titleDiv.find('i', class_ = 'verified-icon')) 167 | # The username in the channel info is not canonicalised, nor is the one on the /channel page anywhere. 168 | # However, the post URLs are, so extract the first post and use that. 169 | try: 170 | kwargs['username'] = next(self._soup_to_items(soup, r.url, onlyUsername = True)) 171 | except StopIteration: 172 | # If there are no posts, fall back to the channel info div, although that should never happen due to the 'Channel created' entry. 173 | _logger.warning('Could not find a post; extracting username from channel info div, which may not be capitalised correctly') 174 | kwargs['username'] = channelInfoDiv.find('div', class_ = 'tgme_channel_info_header_username').text[1:] # Remove @ 175 | if (descriptionDiv := channelInfoDiv.find('div', class_ = 'tgme_channel_info_description')): 176 | kwargs['description'] = descriptionDiv.text 177 | 178 | def parse_num(s): 179 | s = s.replace(' ', '') 180 | if s.endswith('M'): 181 | return int(float(s[:-1]) * 1e6), 10 ** (6 if '.' not in s else 6 - len(s[:-1].split('.')[1])) 182 | elif s.endswith('K'): 183 | return int(float(s[:-1]) * 1000), 10 ** (3 if '.' not in s else 3 - len(s[:-1].split('.')[1])) 184 | else: 185 | return int(s), 1 186 | 187 | for div in channelInfoDiv.find_all('div', class_ = 'tgme_channel_info_counter'): 188 | value, granularity = parse_num(div.find('span', class_ = 'counter_value').text) 189 | type_ = div.find('span', class_ = 'counter_type').text 190 | if type_ == 'members': 191 | # Already extracted more accurately from /channel, skip 192 | continue 193 | elif type_ in ('photos', 'videos', 'links', 'files'): 194 | kwargs[type_] = snscrape.base.IntWithGranularity(value, granularity) 195 | 196 | return Channel(**kwargs) 197 | 198 | @classmethod 199 | def _cli_setup_parser(cls, subparser): 200 | subparser.add_argument('channel', type = snscrape.utils.nonempty_string_arg('channel'), help = 'A channel name') 201 | 202 | @classmethod 203 | def _cli_from_args(cls, args): 204 | return cls._cli_construct(args, args.channel) 205 | -------------------------------------------------------------------------------- /snscrape/modules/vkontakte.py: -------------------------------------------------------------------------------- 1 | __all__ = ['VKontaktePost', 'Photo', 'PhotoVariant', 'Video', 'User', 'VKontakteUserScraper'] 2 | 3 | 4 | import bs4 5 | import collections 6 | import dataclasses 7 | import datetime 8 | import itertools 9 | import json 10 | import logging 11 | import re 12 | import snscrape.base 13 | import snscrape.utils 14 | import typing 15 | import urllib.parse 16 | try: 17 | import zoneinfo 18 | except ImportError: 19 | # Python 3.8 support; nowadays, Europe/Moscow is always UTC+3, but it's more complicated before 2014, so need proper zone info 20 | import pytz 21 | def _timezone(s): 22 | return pytz.timezone(s) 23 | def _localised_datetime(tz, *args, **kwargs): 24 | return tz.localize(datetime.datetime(*args, **kwargs)) 25 | else: 26 | def _timezone(s): 27 | return zoneinfo.ZoneInfo(s) 28 | def _localised_datetime(tz, *args, **kwargs): 29 | return datetime.datetime(*args, tzinfo = tz, **kwargs) 30 | 31 | 32 | _logger = logging.getLogger(__name__) 33 | _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] 34 | _datePattern = re.compile(r'^(?Ptoday' 35 | r'|yesterday' 36 | r'|(?P\d+)\s+(?P' + '|'.join(_months) + r')(\s+(?P\d{4}))?' 37 | r'|(?P' + '|'.join(_months) + r')\s+(?P\d+),\s+(?P\d{4})' 38 | ')' 39 | r'\s+at\s+(?P\d+):(?P\d+)\s+(?P[ap]m)$') 40 | 41 | 42 | @dataclasses.dataclass 43 | class VKontaktePost(snscrape.base.Item): 44 | url: str 45 | date: typing.Optional[typing.Union[datetime.datetime, datetime.date]] 46 | content: str 47 | outlinks: typing.Optional[typing.List[str]] = None 48 | photos: typing.Optional[typing.List['Photo']] = None 49 | video: typing.Optional['Video'] = None 50 | quotedPost: typing.Optional['VKontaktePost'] = None 51 | 52 | def __str__(self): 53 | return self.url 54 | 55 | 56 | @dataclasses.dataclass 57 | class Photo: 58 | variants: typing.List['PhotoVariant'] 59 | url: typing.Optional[str] = None 60 | 61 | 62 | @dataclasses.dataclass 63 | class PhotoVariant: 64 | url: str 65 | width: int 66 | height: int 67 | 68 | 69 | @dataclasses.dataclass 70 | class Video: 71 | id: str 72 | list: str 73 | duration: int 74 | url: str 75 | thumbUrl: str 76 | 77 | 78 | @dataclasses.dataclass 79 | class User(snscrape.base.Item): 80 | username: str 81 | name: str 82 | verified: bool 83 | description: typing.Optional[str] = None 84 | websites: typing.Optional[typing.List[str]] = None 85 | followers: typing.Optional[snscrape.base.IntWithGranularity] = None 86 | posts: typing.Optional[snscrape.base.IntWithGranularity] = None 87 | photos: typing.Optional[snscrape.base.IntWithGranularity] = None 88 | tags: typing.Optional[snscrape.base.IntWithGranularity] = None 89 | following: typing.Optional[snscrape.base.IntWithGranularity] = None 90 | 91 | followersGranularity = snscrape.base._DeprecatedProperty('followersGranularity', lambda self: self.followers.granularity, 'followers.granularity') 92 | postsGranularity = snscrape.base._DeprecatedProperty('postsGranularity', lambda self: self.posts.granularity, 'posts.granularity') 93 | photosGranularity = snscrape.base._DeprecatedProperty('photosGranularity', lambda self: self.photos.granularity, 'photos.granularity') 94 | tagsGranularity = snscrape.base._DeprecatedProperty('tagsGranularity', lambda self: self.tags.granularity, 'tags.granularity') 95 | followingGranularity = snscrape.base._DeprecatedProperty('followingGranularity', lambda self: self.following.granularity, 'following.granularity') 96 | 97 | def __str__(self): 98 | return f'https://vk.com/{self.username}' 99 | 100 | 101 | class VKontakteUserScraper(snscrape.base.Scraper): 102 | name = 'vkontakte-user' 103 | 104 | def __init__(self, username, **kwargs): 105 | super().__init__(**kwargs) 106 | self._username = username 107 | self._baseUrl = f'https://vk.com/{self._username}' 108 | self._headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0', 'Accept-Language': 'en-US,en;q=0.5'} 109 | self._initialPage = None 110 | self._initialPageSoup = None 111 | 112 | def _away_a_to_url(self, a): 113 | # Transform an tag with an href of /away.php?to=... to a plain URL; returns None if a doesn't have that form. 114 | if a and a.get('href', '').startswith('/away.php?to='): 115 | end = a['href'].find('&', 13) 116 | if end == -1: 117 | end = None 118 | return urllib.parse.unquote(a['href'][13 : end]) 119 | return None 120 | 121 | def is_photo(self, a): 122 | return 'aria-label' in a.attrs and a.attrs['aria-label'].startswith('photo') 123 | 124 | def _date_span_to_date(self, dateSpan): 125 | if not dateSpan: 126 | return None 127 | if 'time' in dateSpan.attrs: 128 | return datetime.datetime.fromtimestamp(int(dateSpan['time']), datetime.timezone.utc) 129 | if (match := _datePattern.match(dateSpan.text)): 130 | # Datetime information down to minutes 131 | tz = _timezone('Europe/Moscow') 132 | if match.group('date') in ('today', 'yesterday'): 133 | date = datetime.datetime.now(tz = tz) 134 | if match.group('date') == 'yesterday': 135 | date -= datetime.timedelta(days = 1) 136 | year, month, day = date.year, date.month, date.day 137 | else: 138 | year = int(match.group('year1') or match.group('year2') or datetime.datetime.now(tz = tz).year) 139 | month = _months.index(match.group('month1') or match.group('month2')) + 1 140 | day = int(match.group('day1') or match.group('day2')) 141 | hour = int(match.group('hour')) 142 | # Damn AM/PM... 143 | if hour == 12: 144 | hour -= 12 145 | if match.group('ampm') == 'pm': 146 | hour += 12 147 | minute = int(match.group('minute')) 148 | return _localised_datetime(tz, year, month, day, hour, minute) 149 | if (match := re.match(r'^(?P\d+)\s+(?P' + '|'.join(_months) + r')\s+(?P\d{4})$', dateSpan.text)): 150 | # Date only 151 | return datetime.date(int(match.group('year')), _months.index(match.group('month')) + 1, int(match.group('day'))) 152 | if dateSpan.text not in ('video', 'photo'): # Silently ignore video and photo reposts which have no original date attached 153 | _logger.warning(f'Could not parse date string: {dateSpan.text!r}') 154 | 155 | def _post_div_to_item(self, post, isCopy = False): 156 | postLink = post.find('a', class_ = 'post_link' if not isCopy else 'published_by_date') 157 | if not postLink: 158 | _logger.warning(f'Skipping post without link: {str(post)[:200]!r}') 159 | return 160 | url = urllib.parse.urljoin(self._baseUrl, postLink['href']) 161 | assert (url.startswith('https://vk.com/wall') or (isCopy and (url.startswith('https://vk.com/video') or url.startswith('https://vk.com/photo')))) and '_' in url and url[-1] != '_' and url.rsplit('_', 1)[1].strip('0123456789') in ('', '?reply=') 162 | if not isCopy: 163 | dateSpan = post.find('div', class_ = 'post_date').find('span', class_ = 'rel_date') 164 | else: 165 | dateSpan = post.find('div', class_ = 'copy_post_date').find('a', class_ = 'published_by_date') 166 | textDiv = post.find('div', class_ = 'wall_post_text') 167 | outlinks = [h for a in textDiv.find_all('a') if (h := self._away_a_to_url(a))] if textDiv else [] 168 | if (mediaLinkDiv := post.find('div', class_ = 'media_link')) and \ 169 | (mediaLinkA := mediaLinkDiv.find('a', class_ = 'media_link__title')) and \ 170 | (href := self._away_a_to_url(mediaLinkA)) and \ 171 | href not in outlinks: 172 | outlinks.append(href) 173 | photos = None 174 | video = None 175 | if (thumbsDiv := (post.find('div', class_ = 'wall_text') if not isCopy else post).find('div', class_ = 'page_post_sized_thumbs')) and \ 176 | not (not isCopy and thumbsDiv.parent.name == 'div' and 'class' in thumbsDiv.parent.attrs and 'copy_quote' in thumbsDiv.parent.attrs['class']): # Skip post quotes 177 | photos = [] 178 | for a in thumbsDiv.find_all('a', class_ = 'page_post_thumb_wrap'): 179 | if not self.is_photo(a) and 'data-video' not in a.attrs: 180 | _logger.warning(f'Skipping non-photo and non-video thumb wrap on {url}') 181 | continue 182 | if 'data-video' in a.attrs: 183 | # Video 184 | video = Video( 185 | id = a['data-video'], 186 | list = a['data-list'], 187 | duration = int(a['data-duration']), 188 | url = f'https://vk.com{a["href"]}', 189 | thumbUrl = a['style'][(begin := a['style'].find('background-image: url(') + 22) : a['style'].find(')', begin)], 190 | ) 191 | continue 192 | # From here on: photo 193 | if 'onclick' not in a.attrs or not a['onclick'].startswith("return showPhoto('") or '{"temp":' not in a['onclick'] or not a['onclick'].endswith('}, event)'): 194 | _logger.warning(f'Photo thumb wrap on {url} has no or unexpected onclick, skipping') 195 | continue 196 | photoData = a['onclick'][a['onclick'].find('{"temp":') : -8] # -8 = len(', event)') 197 | photoObj = json.loads(photoData) 198 | singleLetterKeys = [k for k in photoObj['temp'].keys() if len(k) == 1 and 97 <= ord(k) <= 122] # 97 = ord('a'), 122 = ord('z') 199 | for x in singleLetterKeys: 200 | # Merge base into URLs 201 | if not photoObj['temp'][x].startswith('https://'): 202 | photoObj['temp'][x] = f'{photoObj["temp"]["base"]}{photoObj["temp"][x]}' 203 | x_ = f'{x}_' 204 | if not photoObj['temp'][x_][0].startswith('https://'): 205 | photoObj['temp'][x_][0] = f'{photoObj["temp"]["base"]}{photoObj["temp"][x_][0]}' 206 | if any(k not in {'base', 'w', 'w_', 'x', 'x_', 'y', 'y_', 'z', 'z_'} for k in photoObj['temp'].keys()) or \ 207 | not all(photoObj['temp'][x] in (photoObj['temp'][f'{x}_'][0], photoObj['temp'][f'{x}_'][0] + '.jpg') for x in singleLetterKeys) or \ 208 | not all(photoObj['temp'][x].startswith('https://sun') and '.userapi.com/' in photoObj['temp'][x] for x in singleLetterKeys) or \ 209 | not all(len(photoObj['temp'][(x_ := f'{x}_')]) == 3 and isinstance(photoObj['temp'][x_][1], int) and isinstance(photoObj['temp'][x_][2], int) for x in singleLetterKeys): 210 | _logger.warning(f'Photo thumb wrap on {url} has unexpected data structure, skipping') 211 | continue 212 | photoVariants = [] 213 | for x in singleLetterKeys: 214 | x_ = f'{x}_' 215 | photoVariants.append(PhotoVariant(url = f'{photoObj["temp"][x_][0]}.jpg' if '.jpg' not in photoObj['temp'][x_][0] else photoObj['temp'][x_][0], width = photoObj['temp'][x_][1], height = photoObj['temp'][x_][2])) 216 | photoUrl = f'https://vk.com{a["href"]}' if 'href' in a.attrs and a['href'].startswith('/photo') and a['href'][6:].strip('0123456789-_') == '' else None 217 | photos.append(Photo(variants = photoVariants, url = photoUrl)) 218 | quotedPost = self._post_div_to_item(quoteDiv, isCopy = True) if (quoteDiv := post.find('div', class_ = 'copy_quote')) else None 219 | return VKontaktePost( 220 | url = url, 221 | date = self._date_span_to_date(dateSpan), 222 | content = textDiv.text if textDiv else None, 223 | outlinks = outlinks or None, 224 | photos = photos or None, 225 | video = video or None, 226 | quotedPost = quotedPost, 227 | ) 228 | 229 | def _soup_to_items(self, soup): 230 | for post in soup.find_all('div', class_ = 'post'): 231 | yield self._post_div_to_item(post) 232 | 233 | def _initial_page(self): 234 | if self._initialPage is None: 235 | _logger.info('Retrieving initial data') 236 | r = self._get(self._baseUrl, headers = self._headers) 237 | if r.status_code not in (200, 404): 238 | raise snscrape.base.ScraperException(f'Got status code {r.status_code}') 239 | # VK sends windows-1251-encoded data, but Requests's decoding doesn't seem to work correctly and causes lxml to choke, so we need to pass the binary content and the encoding explicitly. 240 | self._initialPage, self._initialPageSoup = r, bs4.BeautifulSoup(r.content, 'lxml', from_encoding = r.encoding) 241 | return self._initialPage, self._initialPageSoup 242 | 243 | def get_items(self): 244 | r, soup = self._initial_page() 245 | if r.status_code == 404: 246 | _logger.warning('Wall does not exist') 247 | return 248 | 249 | if soup.find('div', class_ = 'profile_closed_wall_dummy'): 250 | _logger.warning('Private profile') 251 | return 252 | 253 | if (profileDeleted := soup.find('h5', class_ = 'profile_deleted_text')): 254 | # Unclear what this state represents, so just log website text. 255 | _logger.warning(profileDeleted.text) 256 | return 257 | 258 | newestPost = soup.find('div', class_ = 'post') 259 | if not newestPost: 260 | _logger.info('Wall has no posts') 261 | return 262 | ownerID = newestPost.attrs['data-post-id'].split('_')[0] 263 | # If there is a pinned post, we need its ID for the pagination requests 264 | if 'post_fixed' in newestPost.attrs['class']: 265 | fixedPostID = int(newestPost.attrs['id'].split('_')[1]) 266 | else: 267 | fixedPostID = '' 268 | 269 | last1000PostIDs = collections.deque(maxlen = 1000) 270 | 271 | def _process_soup(soup): 272 | nonlocal last1000PostIDs 273 | for item in self._soup_to_items(soup): 274 | postID = int(item.url.rsplit('_', 1)[1]) 275 | if postID not in last1000PostIDs: 276 | yield item 277 | last1000PostIDs.append(postID) 278 | 279 | yield from _process_soup(soup) 280 | 281 | lastWorkingOffset = 0 282 | for offset in itertools.count(start = 10, step = 10): 283 | posts = self._get_wall_offset(fixedPostID, ownerID, offset) 284 | if posts.startswith('
'): 285 | # Reached the end 286 | break 287 | if not posts.startswith('
'): 293 | # No breaking the outer loop, it'll just make one extra request and exit as well 294 | break 295 | if not geoPosts.startswith('
typing.Tuple[int, int]: 355 | if s.endswith('K'): 356 | return int(s[:-1]) * 1000, 1000 357 | elif s.endswith('M'): 358 | baseNum = s[:-1] 359 | precision = 1000000 360 | if '.' in s: 361 | precision //= (10 ** len(baseNum.split('.')[1])) 362 | return int(float(baseNum) * 1000000), precision 363 | else: 364 | return int(s.replace(',', '')), 1 365 | 366 | if (countsDiv := soup.find('div', class_ = 'counts_module')): 367 | for a in countsDiv.find_all('a', class_ = 'page_counter'): 368 | count, granularity = parse_num(a.find('div', class_ = 'count').text) 369 | label = a.find('div', class_ = 'label').text 370 | if label in ('follower', 'post', 'photo', 'tag'): 371 | label = f'{label}s' 372 | if label in ('followers', 'posts', 'photos', 'tags'): 373 | kwargs[label] = snscrape.base.IntWithGranularity(count, granularity) 374 | 375 | if (idolsDiv := soup.find('div', id = 'profile_idols')): 376 | if (topDiv := idolsDiv.find('div', class_ = 'header_top')) and topDiv.find('span', class_ = 'header_label').text == 'Following': 377 | kwargs['following'] = snscrape.base.IntWithGranularity(*parse_num(topDiv.find('span', class_ = 'header_count').text)) 378 | 379 | # On public pages, this is where followers are listed 380 | if (followersDiv := soup.find('div', id = 'public_followers')): 381 | if (topDiv := followersDiv.find('div', class_ = 'header_top')) and topDiv.find('span', class_ = 'header_label').text == 'Followers': 382 | kwargs['followers'] = snscrape.base.IntWithGranularity(*parse_num(topDiv.find('span', class_ = 'header_count').text)) 383 | 384 | return User(**kwargs) 385 | 386 | @classmethod 387 | def _cli_setup_parser(cls, subparser): 388 | subparser.add_argument('username', type = snscrape.utils.nonempty_string_arg('username'), help = 'A VK username') 389 | 390 | @classmethod 391 | def _cli_from_args(cls, args): 392 | return cls._cli_construct(args, args.username) 393 | -------------------------------------------------------------------------------- /snscrape/modules/weibo.py: -------------------------------------------------------------------------------- 1 | __all__ = ['Post', 'User', 'WeiboUserScraper'] 2 | 3 | 4 | import dataclasses 5 | import logging 6 | import re 7 | import snscrape.base 8 | import snscrape.utils 9 | import typing 10 | 11 | 12 | _logger = logging.getLogger(__name__) 13 | _userDoesNotExist = object() 14 | _HTML_STRIP_PATTERN = re.compile(r'<[^>]*>') 15 | 16 | 17 | @dataclasses.dataclass 18 | class Post(snscrape.base.Item): 19 | url: str 20 | id: str 21 | user: typing.Optional['User'] 22 | createdAt: str # Can have a variety of inconsistent formats 23 | text: str 24 | repostsCount: typing.Optional[int] 25 | commentsCount: typing.Optional[typing.Union[int, str]] 26 | likesCount: typing.Optional[int] 27 | picturesCount: typing.Optional[int] 28 | pictures: typing.Optional[typing.List[str]] # May be shorter than pictureCount if the API didn't return all of them (e.g. post Ipay2evb0) 29 | video: typing.Optional[str] 30 | link: typing.Optional[str] 31 | repostedPost: typing.Optional['Post'] 32 | 33 | def __str__(self): 34 | return self.url 35 | 36 | 37 | @dataclasses.dataclass 38 | class User(snscrape.base.Item): 39 | screenname: str 40 | uid: int 41 | verified: bool 42 | verifiedReason: typing.Optional[str] 43 | description: str 44 | statusesCount: int 45 | followersCount: int 46 | followCount: int 47 | avatar: str 48 | 49 | def __str__(self): 50 | return f'https://m.weibo.cn/u/{self.uid}' 51 | 52 | 53 | class WeiboUserScraper(snscrape.base.Scraper): 54 | name = 'weibo-user' 55 | 56 | def __init__(self, user, **kwargs): 57 | super().__init__(**kwargs) 58 | self._user = user 59 | self._isUserId = isinstance(user, int) 60 | self._headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'} 61 | 62 | def _ensure_user_id(self): 63 | if self._isUserId: 64 | return 65 | r = self._get(f'https://m.weibo.cn/n/{self._user}', headers = self._headers, allowRedirects = False) 66 | if r.status_code == 302 and r.headers['Location'].startswith('/u/') and len(r.headers['Location']) == 13 and r.headers['Location'][3:].strip('0123456789') == '': 67 | # Redirect to uid URL 68 | self._user = int(r.headers['Location'][3:]) 69 | self._isUserId = True 70 | elif r.status_code == 200 and '

用户不存在

' in r.text: 71 | _logger.warning('User does not exist') 72 | self._user = _userDoesNotExist 73 | else: 74 | raise snscrape.base.ScraperException(f'Got unexpected response on resolving username ({r.status_code})') 75 | 76 | def _check_timeline_response(self, r): 77 | if r.status_code == 200 and r.content == b'{"ok":0,"msg":"\\u8fd9\\u91cc\\u8fd8\\u6ca1\\u6709\\u5185\\u5bb9","data":{"cards":[]}}': 78 | # 'No content here yet'. Appears to happen sometimes on pagination, possibly due to too fast requests; retry this 79 | return False, 'no-content message' 80 | if r.status_code != 200: 81 | return False, 'non-200 status code' 82 | return True, None 83 | 84 | def _mblog_to_item(self, mblog): 85 | if mblog.get('page_info', {}).get('type') not in (None, 'video', 'webpage'): 86 | _logger.warning(f'Skipping unknown page info {mblog["page_info"]["type"]!r} on status {mblog["id"]}') 87 | return Post( 88 | url = f'https://m.weibo.cn/status/{mblog["bid"]}', 89 | id = mblog['id'], 90 | user = self._user_info_to_entity(mblog['user']) if mblog['user'] is not None else None, 91 | createdAt = mblog['created_at'], 92 | text = mblog['raw_text'] if 'raw_text' in mblog else _HTML_STRIP_PATTERN.sub('', mblog['text']), 93 | repostsCount = mblog.get('reposts_count'), 94 | commentsCount = mblog.get('comments_count'), 95 | likesCount = mblog.get('attitudes_count'), 96 | picturesCount = mblog.get('pic_num'), 97 | pictures = [x['large']['url'] for x in mblog['pics']] if 'pics' in mblog else None, 98 | video = urls.get('mp4_720p_mp4') or urls.get('mp4_hd_mp4') or urls['mp4_ld_mp4'] if 'page_info' in mblog and mblog['page_info']['type'] == 'video' and (urls := mblog['page_info']['urls']) else None, 99 | link = mblog['page_info']['page_url'] if 'page_info' in mblog and mblog['page_info']['type'] == 'webpage' else None, 100 | repostedPost = self._mblog_to_item(mblog['retweeted_status']) if 'retweeted_status' in mblog else None, 101 | ) 102 | 103 | def get_items(self): 104 | self._ensure_user_id() 105 | if self._user is _userDoesNotExist: 106 | return 107 | sinceId = None 108 | while True: 109 | sinceParam = f'&since_id={sinceId}' if sinceId is not None else '' 110 | r = self._get(f'https://m.weibo.cn/api/container/getIndex?type=uid&value={self._user}&containerid=107603{self._user}&count=25{sinceParam}', headers = self._headers, responseOkCallback = self._check_timeline_response) 111 | if r.status_code != 200: 112 | raise snscrape.base.ScraperException(f'Got status code {r.status_code}') 113 | o = r.json() 114 | for card in o['data']['cards']: 115 | if card['card_type'] != 9: 116 | _logger.warning(f'Skipping card of type {card["card_type"]}') 117 | continue 118 | yield self._mblog_to_item(card['mblog']) 119 | if 'since_id' not in o['data']['cardlistInfo']: 120 | # End of pagination 121 | break 122 | sinceId = o['data']['cardlistInfo']['since_id'] 123 | 124 | def _user_info_to_entity(self, userInfo): 125 | return User( 126 | screenname = userInfo['screen_name'], 127 | uid = userInfo['id'], 128 | verified = userInfo['verified'], 129 | verifiedReason = userInfo.get('verified_reason'), 130 | description = userInfo['description'], 131 | statusesCount = userInfo['statuses_count'], 132 | followersCount = userInfo['followers_count'], 133 | followCount = userInfo['follow_count'], 134 | avatar = userInfo['avatar_hd'], 135 | ) 136 | 137 | def _get_entity(self): 138 | self._ensure_user_id() 139 | if self._user is _userDoesNotExist: 140 | return 141 | r = self._get(f'https://m.weibo.cn/api/container/getIndex?type=uid&value={self._user}', headers = self._headers) 142 | if r.status_code != 200: 143 | raise snscrape.base.ScraperException('Could not fetch user info') 144 | o = r.json() 145 | return self._user_info_to_entity(o['data']['userInfo']) 146 | 147 | @classmethod 148 | def _cli_setup_parser(cls, subparser): 149 | subparser.add_argument('--name', dest = 'isName', action = 'store_true', help = 'Use username instead of user ID') 150 | subparser.add_argument('user', type = snscrape.utils.nonempty_string_arg('user'), help = 'A user ID') 151 | 152 | @classmethod 153 | def _cli_from_args(cls, args): 154 | return cls._cli_construct(args, user = args.user if args.isName else int(args.user)) 155 | -------------------------------------------------------------------------------- /snscrape/utils.py: -------------------------------------------------------------------------------- 1 | def dict_map(input, keyMap): 2 | '''Return a new dict from an input dict and a {'input_key': 'output_key'} mapping''' 3 | 4 | return {outputKey: input[inputKey] for inputKey, outputKey in keyMap.items() if inputKey in input} 5 | 6 | 7 | def snake_to_camel(**kwargs): 8 | '''Return a new dict from kwargs with snake_case keys replaced by camelCase''' 9 | 10 | out = {} 11 | for key, value in kwargs.items(): 12 | keyParts = key.split('_') 13 | for i in range(1, len(keyParts)): 14 | keyParts[i] = keyParts[i][:1].upper() + keyParts[i][1:] 15 | out[''.join(keyParts)] = value 16 | return out 17 | 18 | 19 | def nonempty_string_arg(name): 20 | '''An argparse argument type factory for a non-empty string argument. The supplied `name` is used for the internal function name, resulting in better error messages.''' 21 | 22 | def f(s): 23 | s = s.strip() 24 | if s: 25 | return s 26 | raise ValueError('must not be an empty string') 27 | f.__name__ = name 28 | return f 29 | 30 | 31 | def module_deprecation_helper(all, **names): 32 | '''A helper function to generate the relevant module __getattr__ and __dir__ functions for handling deprecated names''' 33 | 34 | def __getattr__(name): 35 | if name in names: 36 | warnings.warn(f'{name} is deprecated, use {names[name].__name__} instead', DeprecatedFeatureWarning, stacklevel = 2) 37 | return names[name] 38 | raise AttributeError(f'module {__name__!r} has no attribute {name!r}') 39 | def __dir__(): 40 | return sorted(all + list(names.keys())) 41 | return __getattr__, __dir__ 42 | -------------------------------------------------------------------------------- /snscrape/version.py: -------------------------------------------------------------------------------- 1 | import importlib.metadata 2 | 3 | 4 | try: 5 | __version__ = importlib.metadata.version('snscrape') 6 | except importlib.metadata.PackageNotFoundError: 7 | __version__ = None 8 | --------------------------------------------------------------------------------