├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── BUILD.md ├── CODE_OF_CONDUCT.md ├── LICENSE.txt ├── MANIFEST.in ├── Makefile ├── README.md ├── USAGE.md ├── docs ├── CONTRIBUTING.md ├── Makefile ├── _static │ └── .gitignore ├── authors.rst ├── conf.py ├── index.rst └── license.rst ├── requirements-test.txt ├── requirements.txt ├── setup.py ├── tests ├── __init__.py ├── conftest.py ├── test_conversation_tweets.py ├── test_profile_tweets.py ├── test_search_tweets.py └── test_users_scrape.py └── tweetscrape ├── __init__.py ├── conversation_tweets.py ├── model ├── __init__.py ├── tweet_model.py └── user_model.py ├── profile_tweets.py ├── search_tweets.py ├── tweets_scrape.py ├── twitter_scrape.py └── users_scrape.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Temporary and binary files 2 | *~ 3 | *.py[cod] 4 | *.so 5 | *.cfg 6 | !setup.cfg 7 | *.orig 8 | *.log 9 | *.pot 10 | __pycache__/* 11 | .cache/* 12 | .*.swp 13 | */.ipynb_checkpoints/* 14 | 15 | # Project files 16 | .ropeproject 17 | .project 18 | .pydevproject 19 | .settings 20 | .idea 21 | .vscode/* 22 | 23 | # Package files 24 | *.egg 25 | *.eggs/ 26 | .installed.cfg 27 | *.egg-info 28 | 29 | # Unittest and coverage 30 | htmlcov/* 31 | .coverage 32 | .tox 33 | junit.xml 34 | coverage.xml 35 | .pytest_cache/* 36 | 37 | # Build and docs folder/files 38 | build/* 39 | dist/* 40 | sdist/* 41 | docs/api/* 42 | docs/_build/* 43 | cover/* 44 | MANIFEST 45 | 46 | # Django stuff: 47 | *.log 48 | local_settings.py 49 | 50 | # Scrapy stuff: 51 | .scrapy 52 | 53 | # Jupyter Notebook 54 | .ipynb_checkpoints 55 | 56 | # pyenv 57 | .python-version 58 | 59 | # virtualenv 60 | .venv 61 | venv/ 62 | ENV/ 63 | 64 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: python 3 | 4 | python: 5 | - "3.5" 6 | - "3.6" 7 | 8 | os: 9 | - linux 10 | 11 | #virtualenv: 12 | # system_site_packages: true 13 | 14 | branches: 15 | only: 16 | - master 17 | 18 | before_install: 19 | - pip install -r requirements-test.txt 20 | 21 | install: 22 | - pip install -r requirements.txt 23 | 24 | script: 25 | - pytest --cov=tweetscrape 26 | 27 | after_success: 28 | - codecov 29 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributors 3 | ============ 4 | 5 | * 5hirish 6 | -------------------------------------------------------------------------------- /BUILD.md: -------------------------------------------------------------------------------- 1 | #### Release Build 2 | 3 | 1) Run all PyTest test cases 4 | 2) Update the version number 5 | 3) Build source and wheels packages 6 | 4) Upload to PyPi via Twine 7 | 8 | ```bash 9 | $ python setup.py sdist bdist_wheel 10 | $ twine upload dist/* 11 | $ pip install tweetscrape --upgrade 12 | ``` 13 | 14 | #### Edit Mode Install 15 | 16 | ```bash 17 | $ pip install -e . 18 | ``` -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at shirishkadam35@yahoo.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE.txt README.md USAGE.md AUTHORS.rst -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/bash 2 | sha = $(shell "git" "rev-parse" "--short" "HEAD") 3 | 4 | dist/tweetscrape.pex : tweetscrape/*.py* tweetscrape/*/*.py* 5 | python3.6 -m venv env 6 | source env/bin/activate 7 | env/bin/pip install wheel 8 | env/bin/pip install -r requirements.txt --no-cache-dir 9 | env/bin/python setup.py build_ext --inplace 10 | env/bin/python setup.py sdist 11 | env/bin/python setup.py bdist_wheel 12 | env/bin/python -m pip install pex==1.6.7 13 | env/bin/pex pytest dist/*.whl -e tweetscrape -o dist/tweetscrape-$(sha).pex 14 | cp dist/tweetscrape-$(sha).pex dist/tweetscrape.pex 15 | chmod a+rx dist/tweetscrape.pex 16 | 17 | .PHONY : clean 18 | 19 | clean : setup.py 20 | source env/bin/activate 21 | rm -rf dist/* 22 | python setup.py clean --all -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Tweet Scrapper 2 | 3 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) 4 | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/5924d3402a2c43d0bf7affa6863872f6)](https://www.codacy.com/app/5hirish/tweet_scrapper?utm_source=github.com&utm_medium=referral&utm_content=5hirish/tweet_scrapper&utm_campaign=Badge_Grade) 5 | [![codecov](https://codecov.io/gh/5hirish/tweet_scrapper/branch/master/graph/badge.svg)](https://codecov.io/gh/5hirish/tweet_scrapper) 6 | [![Build Status](https://travis-ci.org/5hirish/tweet_scrapper.svg?branch=master)](https://travis-ci.org/5hirish/tweet_scrapper) 7 | [![Current Release Version](https://img.shields.io/github/release/5hirish/tweet_scrapper.svg)](https://github.com/5hirish/tweet_scrapper/releases) 8 | [![pypi Version](https://img.shields.io/pypi/v/tweetscrape.svg)](https://pypi.python.org/pypi/tweetscrape) 9 | [![Twitter](https://img.shields.io/twitter/follow/openebs.svg?style=social&label=Follow)](https://twitter.com/intent/follow?screen_name=5hirish) 10 | 11 | 12 | Twitter's API is annoying to work with, and has lots of limitations — luckily their frontend (JavaScript) has it's own API, which I reverse–engineered. No API rate limits. No restrictions. Extremely fast. 13 | 14 | You can use this library to get the text of any user's Tweets trivially. Follow the creator's blog at [shirishkadam.com](https://shirishkadam.com) for updates on progress. 15 | 16 | ## Installation 17 | Built for Python 3.5.x, 3.6.x 18 | 19 | ```bash 20 | $ pip install tweetscrape 21 | $ python -m tweetscrape.twitter_scrape --help 22 | ``` 23 | 24 | ## Getting Started 25 | ```bash 26 | $ python -m tweetscrape.twitter_scrape -u "5hirish" -n 60 -d "twitter.csv" -f "csv" 27 | $ python -m tweetscrape.twitter_scrape --hashtag "#Python" -n 60 -d "twitter.csv" -f "csv" 28 | $ python -m tweetscrape.twitter_scrape --all "Avengers" --mention "@Marvel" -n 20 -d "twitter.csv" -f "csv" 29 | $ python -m tweetscrape.twitter_scrape --near "Brooklyn" -n 20 -d "twitter.csv" -f "csv" 30 | $ python -m tweetscrape.twitter_scrape --from "@CNN" --since "2019-06-20" --until "2019-06-23" -n 20 -d "twitter.csv" -f "csv" 31 | ``` 32 | 33 | ## Usage 34 | 35 | ```python 36 | from tweetscrape.profile_tweets import TweetScrapperProfile 37 | 38 | tweet_scrapper = TweetScrapperProfile("5hirish", 40, 'twitter.csv', 'csv') 39 | tweet_count, tweet_id, tweet_time, dump_path = tweet_scrapper.get_profile_tweets() 40 | print("Extracted {0} tweets till {1} at {2}".format(tweet_count, tweet_time, dump_path)) 41 | ``` 42 | #### Read more on `tweetscrape` usage here: [USAGE.md](USAGE.md) 43 | ```csv 44 | id,type,time,author,author_id,re_tweeter,associated_tweet,text,links,hashtags,mentions,reply_count,favorite_count,retweet_count 45 | 993872079274508289,tweet,1525792543000,5hirish,428808036,,993872079274508289,"Built @twitter #scrapper inspired by @kennethreitz similar project. Does a bunch of other cool stuff like extracting user tweets with all meta-data, hastags, images, likes, etc. extracting tweets based on keyword or hastag search #python @Github https://github.com/5hirish/tweet_scrapper …pic.twitter.com/bXdnrWXNwr","['https://t.co/ID5hJ6InIu', 'https://t.co/bXdnrWXNwr']","['#scrapper', '#python']","['@Twitter', '@kennethreitz', '@github']",1,14,7 46 | 1141791578970894338,tweet,1561059300000,gracecondition,127701253,5hirish,1141791578970894338,everyone else using word2vec:king – man + woman = queenme using word2vec:fish + music = bassfish + friend = chumfish + hair = mulletfish + struggle = flounderoink - pig + bro = wassupyeti – snow + economics = homo economicushttps://graceavery.com/word2vec-fish-music-bass/ …,['https://t.co/UAiViuEnM2'],[],[],17,939,227 47 | 1141849459342610437,tweet,1561073100000,Reuters,1652541,5hirish,1141849459342610437,WATCH: Elon Musk gives #E3 audience a preview of gaming in Tesla carspic.twitter.com/u7rVedhDyW,['https://t.co/u7rVedhDyW'],"['#E3', '#E3']",[],3,49,18 48 | 1141812196453699584,tweet,1561064216000,xamat,9316452,5hirish,1141812196453699584,"The annoying pop-up about cookies on websites is basically teaching me to click ""ok"" on anything that gets in my way asap, which seems very dangerous and exactly the opposite of what is intended.",[],[],[],1,23,3 49 | 1141897990627446784,tweet,1561084671000,data_mike_j,1053368990695706624,5hirish,1141897990627446784,Check out my newest blog post where I build a graph visualization of the #MuellerReport using @spacy_io and #Python including paragraph recommendation engine.https://minimizeuncertainty.com/post/graph-visualization-of-the-mueller-report-with-spacy-and-pyvis/ …,['https://t.co/Q5GGKqmbYv'],"['#MuellerReport', '#Python']",['@spacy_io'],0,31,13 50 | 1142137189775507456,tweet,1561141700000,5hirish,428808036,,1142137187783213056,"Share your weekend goals here, could be anything, like reading a book, writing a blog post, preparing your favorite dessert or anything that will give you a positive feeling of #accomplishment for the coming week. Let's check back on Monday.",[],['#accomplishment'],[],1,0,0 51 | 1142137187783213056,tweet,1561141700000,5hirish,428808036,,1142137187783213056,"Weekend Goal: Convert my Flask app into a RESTful Flask API app template with Unit tests, Travis CI and Swagger docs. #python Repo: https://github.com/5hirish/flask-restful-template … (Contributors Welcome!)#weekendgoal #accountability",['https://t.co/m7isdCd6cc'],"['#python', '#weekendgoal', '#accountability']",[],1,3,1 52 | 1141840676394434560,tweet,1561071006000,naval,745273,5hirish,1141840676394434560,"Lasting novels don’t come from literature departments. Successful businesses don’t come from business schools. Scientific revolutions don’t come from research universities.Get your education, then get moving. Find the loners tinkering at the edge.",[],[],[],149,10188,2562 53 | 1141740790542213121,tweet,1561047191000,WSJ,3108351,5hirish,1141740790542213121,"Slack shares open at $38.50 in their trading debut, above $26 reference price and giving the company a valuation of about $23.2 billionhttps://on.wsj.com/2Xmkitn",['https://t.co/uo7yCGqSmC'],[],[],3,76,48 54 | 1141511813709717504,tweet,1560992599000,quocleix,989251872107085824,5hirish,1141511813709717504,"XLNet: a new pretraining method for NLP that significantly improves upon BERT on 20 tasks (e.g., SQuAD, GLUE, RACE)arxiv: https://arxiv.org/abs/1906.08237 github (code + pretrained models): https://github.com/zihangdai/xlnet with Zhilin Yang, @ZihangDai, Yiming Yang, Jaime Carbonell, @rsalakhupic.twitter.com/JboOekUVPQ","['https://t.co/C1tFMwZvyW', 'https://t.co/kI4jsVzT1u', 'https://t.co/JboOekUVPQ']",[],"['@ZihangDai', '@rsalakhu']",21,1763,715 55 | 1141736965311569920,tweet,1561046279000,justinkan,28917111,5hirish,1141736965311569920,"One of the most important skills I’ve built is the ability to sit with discomfort. Being able to be uncomfortable (bored, on the receiving end of anger, in pain) and not needing to escape has changed my happiness and my life. It would have seemed impossible to me 12 months ago.",[],[],[],38,1578,242 56 | .... 57 | ``` 58 | 59 | ## Requirements 60 | 61 | * [Python 3.X](https://docs.python.org/3/) 62 | 63 | Python Package dependencies listed in [requirements.txt](requirements.txt) 64 | 65 | ### Features 66 | 67 | * Extract user tweets with all meta-data 68 | * Extracts external links, hashtags and mentions from a tweet 69 | * Extracts reply, favorite and retweet counts of a tweet 70 | * Exports data to file in CSV or JSON with UTF-8 encoding 71 | * Scraps tweets in a recursive and greedy approach 72 | * Supports Proxy requests, request delays 73 | * Extracts user information including bio, location and stats 74 | 75 | ### TODO 76 | 77 | - [x] Extract tweets from a twitter user's profile 78 | - [x] Extract tweets from twitter search with advance filters 79 | - [x] Exports tweets to files 80 | - [x] Supports infinite scroll 81 | - [x] Extract tweets from a twitter thread, given the thread 82 | - [ ] Extract the quoted tweet along with a tweet 83 | 84 | ### Contributions 85 | Please see the [contributing documentation](docs/CONTRIBUTING.md) for some tips on getting started. 86 | 87 | ### Terms and conditions 88 | * You will NOT use this API for marketing purposes (spam, botting, harassment, massive bulk messaging...). 89 | * We do NOT give support to anyone who wants to use this API to send spam or commit other crimes. 90 | * We reserve the right to block any user of this repository that does not meet these conditions. 91 | 92 | ### Legal 93 | This code is in no way affiliated with, authorized, maintained, sponsored or endorsed by Twitter or any of its affiliates or subsidiaries. This is an independent and unofficial API. Use at your own risk. 94 | 95 | ### Maintainers 96 | * [@5hirish](https://github.com/5hirish) - Shirish Kadam 97 | -------------------------------------------------------------------------------- /USAGE.md: -------------------------------------------------------------------------------- 1 | ## Usage 2 | 3 | For bash command line interface help: 4 | ```bash 5 | $ python -m tweetscrape.twitter_scrape -h 6 | ``` 7 | 8 | ### Fetch User Profile Tweets 9 | 10 | ```python 11 | from tweetscrape.profile_tweets import TweetScrapperProfile 12 | 13 | tweet_scrapper = TweetScrapperProfile("5hirish", 40, 'twitter.csv', 'csv') 14 | tweet_count, tweet_id, tweet_time, dump_path = tweet_scrapper.get_profile_tweets() 15 | print("Extracted {0} tweets till {1} at {2}".format(tweet_count, tweet_time, dump_path)) 16 | ``` 17 | 18 | The `TweetScrapperProfile` class scrapes the tweets using Twitter frontend APIs with XPATH queries. 19 | It requires four parameters, the Twitter **username**, the **number of tweets** to scrape 20 | (default tweets scraped are 40), the **file path** to dump 21 | the data and the data **export format**, which can be JSON or CSV. 22 | You can even add proxy to the scraper via `request_proxies` parameter. 23 | __NOTE__: To extract as much tweets as possible set the number of tweets to -1. 24 | 25 | The `get_profile_tweets()` method returns the count of tweets, last extracted tweet id, last extracted tweet time and 26 | the file export path of extracted tweets. 27 | 28 | ```csv 29 | id,type,time,author,author_id,re_tweeter,associated_tweet,text,links,hashtags,mentions,reply_count,favorite_count,retweet_count 30 | 993872079274508289,tweet,1525792543000,5hirish,428808036,,993872079274508289,"Built @twitter #scrapper inspired by @kennethreitz similar project. Does a bunch of other cool stuff like extracting user tweets with all meta-data, hastags, images, likes, etc. extracting tweets based on keyword or hastag search #python @Github https://github.com/5hirish/tweet_scrapper …pic.twitter.com/bXdnrWXNwr","['https://t.co/ID5hJ6InIu', 'https://t.co/bXdnrWXNwr']","['#scrapper', '#python']","['@Twitter', '@kennethreitz', '@github']",1,14,7 31 | 1141791578970894338,tweet,1561059300000,gracecondition,127701253,5hirish,1141791578970894338,everyone else using word2vec:king – man + woman = queenme using word2vec:fish + music = bassfish + friend = chumfish + hair = mulletfish + struggle = flounderoink - pig + bro = wassupyeti – snow + economics = homo economicushttps://graceavery.com/word2vec-fish-music-bass/ …,['https://t.co/UAiViuEnM2'],[],[],17,939,227 32 | 1141849459342610437,tweet,1561073100000,Reuters,1652541,5hirish,1141849459342610437,WATCH: Elon Musk gives #E3 audience a preview of gaming in Tesla carspic.twitter.com/u7rVedhDyW,['https://t.co/u7rVedhDyW'],"['#E3', '#E3']",[],3,49,18 33 | 1141812196453699584,tweet,1561064216000,xamat,9316452,5hirish,1141812196453699584,"The annoying pop-up about cookies on websites is basically teaching me to click ""ok"" on anything that gets in my way asap, which seems very dangerous and exactly the opposite of what is intended.",[],[],[],1,23,3 34 | 1141897990627446784,tweet,1561084671000,data_mike_j,1053368990695706624,5hirish,1141897990627446784,Check out my newest blog post where I build a graph visualization of the #MuellerReport using @spacy_io and #Python including paragraph recommendation engine.https://minimizeuncertainty.com/post/graph-visualization-of-the-mueller-report-with-spacy-and-pyvis/ …,['https://t.co/Q5GGKqmbYv'],"['#MuellerReport', '#Python']",['@spacy_io'],0,31,13 35 | 1142137189775507456,tweet,1561141700000,5hirish,428808036,,1142137187783213056,"Share your weekend goals here, could be anything, like reading a book, writing a blog post, preparing your favorite dessert or anything that will give you a positive feeling of #accomplishment for the coming week. Let's check back on Monday.",[],['#accomplishment'],[],1,0,0 36 | 1142137187783213056,tweet,1561141700000,5hirish,428808036,,1142137187783213056,"Weekend Goal: Convert my Flask app into a RESTful Flask API app template with Unit tests, Travis CI and Swagger docs. #python Repo: https://github.com/5hirish/flask-restful-template … (Contributors Welcome!)#weekendgoal #accountability",['https://t.co/m7isdCd6cc'],"['#python', '#weekendgoal', '#accountability']",[],1,3,1 37 | 1141840676394434560,tweet,1561071006000,naval,745273,5hirish,1141840676394434560,"Lasting novels don’t come from literature departments. Successful businesses don’t come from business schools. Scientific revolutions don’t come from research universities.Get your education, then get moving. Find the loners tinkering at the edge.",[],[],[],149,10188,2562 38 | 1141740790542213121,tweet,1561047191000,WSJ,3108351,5hirish,1141740790542213121,"Slack shares open at $38.50 in their trading debut, above $26 reference price and giving the company a valuation of about $23.2 billionhttps://on.wsj.com/2Xmkitn",['https://t.co/uo7yCGqSmC'],[],[],3,76,48 39 | 1141511813709717504,tweet,1560992599000,quocleix,989251872107085824,5hirish,1141511813709717504,"XLNet: a new pretraining method for NLP that significantly improves upon BERT on 20 tasks (e.g., SQuAD, GLUE, RACE)arxiv: https://arxiv.org/abs/1906.08237 github (code + pretrained models): https://github.com/zihangdai/xlnet with Zhilin Yang, @ZihangDai, Yiming Yang, Jaime Carbonell, @rsalakhupic.twitter.com/JboOekUVPQ","['https://t.co/C1tFMwZvyW', 'https://t.co/kI4jsVzT1u', 'https://t.co/JboOekUVPQ']",[],"['@ZihangDai', '@rsalakhu']",21,1763,715 40 | 1141736965311569920,tweet,1561046279000,justinkan,28917111,5hirish,1141736965311569920,"One of the most important skills I’ve built is the ability to sit with discomfort. Being able to be uncomfortable (bored, on the receiving end of anger, in pain) and not needing to escape has changed my happiness and my life. It would have seemed impossible to me 12 months ago.",[],[],[],38,1578,242 41 | .... 42 | ``` 43 | 44 | ### Fetch Advance Search Tweets 45 | 46 | ```python 47 | from tweetscrape.search_tweets import TweetScrapperSearch 48 | 49 | tweet_scrapper = TweetScrapperSearch(search_from_accounts="@CNN", search_till_date="2016-04-01", search_since_date="2015-11-01", num_tweets=40, tweet_dump_path='twitter.csv', tweet_dump_format='csv') 50 | tweet_count, tweet_id, tweet_time, dump_path = tweet_scrapper.get_search_tweets() 51 | print("Extracted {0} tweets till {1} at {2}".format(tweet_count, tweet_time, dump_path)) 52 | ``` 53 | 54 | The `TweetScrapperSearch` class scrapes the tweets based on the hashtags or a search term or any of the 55 | advanced filters of Twitter search [Twitter Search Advance](https://twitter.com/search-advanced). 56 | It requires multiple parameters, based on the filters you might want to search with. Based on these filters a query is 57 | constructed and searched on Twitter. It also requires the **number of tweets** to scrape, the **file path** to dump 58 | the data and the data **export format**, which can be JSON or CSV. 59 | You can even add proxy to the scraper via `request_proxies` parameter. 60 | 61 | The `get_search_tweets()` method returns the count of tweets, last extracted tweet id, last extracted tweet time and 62 | the file export path of extracted tweets. 63 | 64 | Following are the supported search filters (parameters) for `TweetScrapperSearch` class. 65 | 66 | ```text 67 | search_all: Search all of these words. eg. Avengers Infinity War 68 | search_exact: Search this exact phrase. eg. Avengers 69 | search_any: Search any of these words. eg. SpiderMan Thor Hulk 70 | search_excludes: Search excluding these words. eg. AntMan 71 | search_hashtags: Search these hashtags. eg. #avengers #endgame 72 | search_from_accounts: Search tweets from these accounts. eg. @marvel @avengers 73 | search_to_accounts: Search tweets to these accounts. eg. @marvel 74 | search_mentions: Search tweets mentioning these accounts. eg. @avengers 75 | search_near_place: Search tweets near this place. eg. New York 76 | search_till_date: Search tweets until this date: YYYY-MM-DD eg. 2019-01-01 77 | search_since_date: Search tweets since this date: YYYY-MM-DD. eg. 2018-11-01 78 | language: Search tweets in language from language codes. eg. 'en' for English 79 | ``` 80 | 81 | ### Fetch User Tweet thread Tweets 82 | 83 | ```python 84 | from tweetscrape.conversation_tweets import TweetScrapperConversation 85 | 86 | tweet_scrapper = TweetScrapperConversation("ewarren", 1146415363460141057, 40, 'twitter.csv', 'csv') 87 | tweet_count, tweet_id, tweet_time, dump_path = tweet_scrapper.get_thread_tweets() 88 | print("Extracted {0} tweets till {1} at {2}".format(tweet_count, tweet_time, dump_path)) 89 | ``` 90 | 91 | The `TweetScrapperConversation` class scrapes the tweets from a tweet tread or conversation. 92 | It requires two parameters, the Twitter username of the user who tweeted the original tweet and 93 | the id of the tweet. It also requires the **number of tweets** to scrape, the **file path** to dump 94 | the data and the data **export format**, which can be JSON or CSV. 95 | You can even add proxy to the scraper via `request_proxies` parameter. 96 | 97 | The `get_thread_tweets()` method returns the count of tweets, last extracted tweet id, last extracted tweet time and 98 | the file export path of extracted tweets. 99 | 100 | 101 | ### Fetch User stats 102 | 103 | ```python 104 | from tweetscrape.users_scrape import TweetScrapperUser 105 | 106 | ts = TweetScrapperUser("5hirish") 107 | user_info = ts.get_profile_info() 108 | ``` 109 | 110 | The `TweetScrapperUser` class scrapes the stats of the user from Twitter. 111 | It requires one parameter, the Twitter username of the user. 112 | You can even add proxy to the scraper via `request_proxies` parameter. 113 | 114 | The `get_profile_info()` method returns the JSON with user information. 115 | ```json 116 | { 117 | "username": "@5hirish", 118 | "name": "Shirish Kadam", 119 | "bio": "Building @alleviate_hq #SaaS #NLProc #MachineLearning #DataScience\nAutomating Automation\nhttp://5hirish.com", 120 | "location": "Bengaluru, India", 121 | "location_id": "1b8680cd52a711cb", 122 | "url": "http://www.shirishkadam.com", 123 | "tweets": "2619", 124 | "following": "694", 125 | "followers": "243", 126 | "favorites": "8112" 127 | } 128 | ``` 129 | 130 | ### Extracted Tweets data model 131 | 132 | Method | Description 133 | --- | --- 134 | `get_tweet_id()` | Fetches the item unique identifier 135 | `get_tweet_type()` | The type of the item eg. `tweet` 136 | `get_tweet_author()` | Twitter username of the author 137 | `get_tweet_author_id()` | Unique identifier of the author 138 | `get_tweet_time_ms()` | Tweet time in milliseconds 139 | `get_tweet_text()` | Original tweet text 140 | `get_tweet_links()` | Extracted external links from the tweet 141 | `get_tweet_hashtags()` | Extracted hashtags from the tweet 142 | `get_tweet_mentions()` | Mentioned Twitter users in the tweet 143 | `get_tweet_replies_count()` | Total count of replies on the tweet 144 | `get_tweet_favorite_count()` | Total count of favorites on the tweet 145 | `get_tweet_retweet_count()` | Total count of retweets of the tweet 146 | -------------------------------------------------------------------------------- /docs/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # CONTIRUBING 2 | 3 | Tweet Scrapper is a community-maintained project and we happily accept contributions. 4 | 5 | If you wish to add a new feature or fix a bug: 6 | 7 | 1. Check for [open issues](https://github.com/5hirish/tweet_scrapper/issues) or open a fresh issue to start a discussion around a feature idea or a bug. 8 | 2. Fork the [Tweet Scrapper](https://github.com/5hirish/tweet_scrapper) repository on Github to start making your changes. 9 | 3. Write a test which shows that the bug was fixed or that the feature works as expected. 10 | 4. Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself to [AUTHORS.rst](/AUTHORS.rst). 11 | 12 | ```bash 13 | $ git checkout dev -b feature/my-new-feature 14 | $ git pull origin master 15 | ``` 16 | _Note:_ Follow [PEP8](http://docs.python-guide.org/en/latest/writing/style/) codding style. 17 | 18 | ## Running the tests 19 | 20 | We use some external dependencies, multiple interpreters and code coverage analysis while running test suite. Our Makefile handles much of this for you as long as you’re running it inside of a virtualenv: 21 | ```bash 22 | $ pytest tests 23 | ``` 24 | Our test suite runs continuously on Travis CI with every pull request to `master`. 25 | 26 | ## HELP REQUIRED 27 | 28 | To find where you can help, search for the following tags: 29 | * `#TODO:` The tasks which are pending or yet not taken up 30 | * `#FIXME:` The tasks which require some attending to do 31 | * `#HELP:` The tasks which are require some help 32 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | AUTODOCDIR = api 10 | AUTODOCBUILD = sphinx-apidoc 11 | PROJECT = tweet_scrapper 12 | MODULEDIR = ../src/tweetscap 13 | 14 | # User-friendly check for sphinx-build 15 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $?), 1) 16 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 17 | endif 18 | 19 | # Internal variables. 20 | PAPEROPT_a4 = -D latex_paper_size=a4 21 | PAPEROPT_letter = -D latex_paper_size=letter 22 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 23 | # the i18n builder cannot share the environment and doctrees with the others 24 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 25 | 26 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext doc-requirements 27 | 28 | help: 29 | @echo "Please use \`make ' where is one of" 30 | @echo " html to make standalone HTML files" 31 | @echo " dirhtml to make HTML files named index.html in directories" 32 | @echo " singlehtml to make a single large HTML file" 33 | @echo " pickle to make pickle files" 34 | @echo " json to make JSON files" 35 | @echo " htmlhelp to make HTML files and a HTML help project" 36 | @echo " qthelp to make HTML files and a qthelp project" 37 | @echo " devhelp to make HTML files and a Devhelp project" 38 | @echo " epub to make an epub" 39 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 40 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 41 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 42 | @echo " text to make text files" 43 | @echo " man to make manual pages" 44 | @echo " texinfo to make Texinfo files" 45 | @echo " info to make Texinfo files and run them through makeinfo" 46 | @echo " gettext to make PO message catalogs" 47 | @echo " changes to make an overview of all changed/added/deprecated items" 48 | @echo " xml to make Docutils-native XML files" 49 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 50 | @echo " linkcheck to check all external links for integrity" 51 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 52 | 53 | clean: 54 | rm -rf $(BUILDDIR)/* $(AUTODOCDIR) 55 | 56 | $(AUTODOCDIR): $(MODULEDIR) 57 | mkdir -p $@ 58 | $(AUTODOCBUILD) -f -o $@ $^ 59 | 60 | doc-requirements: $(AUTODOCDIR) 61 | 62 | html: doc-requirements 63 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 64 | @echo 65 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 66 | 67 | dirhtml: doc-requirements 68 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 69 | @echo 70 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 71 | 72 | singlehtml: doc-requirements 73 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 74 | @echo 75 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 76 | 77 | pickle: doc-requirements 78 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 79 | @echo 80 | @echo "Build finished; now you can process the pickle files." 81 | 82 | json: doc-requirements 83 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 84 | @echo 85 | @echo "Build finished; now you can process the JSON files." 86 | 87 | htmlhelp: doc-requirements 88 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 89 | @echo 90 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 91 | ".hhp project file in $(BUILDDIR)/htmlhelp." 92 | 93 | qthelp: doc-requirements 94 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 95 | @echo 96 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 97 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 98 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/$(PROJECT).qhcp" 99 | @echo "To view the help file:" 100 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/$(PROJECT).qhc" 101 | 102 | devhelp: doc-requirements 103 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 104 | @echo 105 | @echo "Build finished." 106 | @echo "To view the help file:" 107 | @echo "# mkdir -p $HOME/.local/share/devhelp/$(PROJECT)" 108 | @echo "# ln -s $(BUILDDIR)/devhelp $HOME/.local/share/devhelp/$(PROJEC)" 109 | @echo "# devhelp" 110 | 111 | epub: doc-requirements 112 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 113 | @echo 114 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 115 | 116 | patch-latex: 117 | find _build/latex -iname "*.tex" | xargs -- \ 118 | sed -i'' 's~includegraphics{~includegraphics\[keepaspectratio,max size={\\textwidth}{\\textheight}\]{~g' 119 | 120 | latex: doc-requirements 121 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 122 | $(MAKE) patch-latex 123 | @echo 124 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 125 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 126 | "(use \`make latexpdf' here to do that automatically)." 127 | 128 | latexpdf: doc-requirements 129 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 130 | $(MAKE) patch-latex 131 | @echo "Running LaTeX files through pdflatex..." 132 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 133 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 134 | 135 | latexpdfja: doc-requirements 136 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 137 | @echo "Running LaTeX files through platex and dvipdfmx..." 138 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 139 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 140 | 141 | text: doc-requirements 142 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 143 | @echo 144 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 145 | 146 | man: doc-requirements 147 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 148 | @echo 149 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 150 | 151 | texinfo: doc-requirements 152 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 153 | @echo 154 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 155 | @echo "Run \`make' in that directory to run these through makeinfo" \ 156 | "(use \`make info' here to do that automatically)." 157 | 158 | info: doc-requirements 159 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 160 | @echo "Running Texinfo files through makeinfo..." 161 | make -C $(BUILDDIR)/texinfo info 162 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 163 | 164 | gettext: doc-requirements 165 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 166 | @echo 167 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 168 | 169 | changes: doc-requirements 170 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 171 | @echo 172 | @echo "The overview file is in $(BUILDDIR)/changes." 173 | 174 | linkcheck: doc-requirements 175 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 176 | @echo 177 | @echo "Link check complete; look for any errors in the above output " \ 178 | "or in $(BUILDDIR)/linkcheck/output.txt." 179 | 180 | doctest: doc-requirements 181 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 182 | @echo "Testing of doctests in the sources finished, look at the " \ 183 | "results in $(BUILDDIR)/doctest/output.txt." 184 | 185 | xml: doc-requirements 186 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 187 | @echo 188 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 189 | 190 | pseudoxml: doc-requirements 191 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 192 | @echo 193 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 194 | -------------------------------------------------------------------------------- /docs/_static/.gitignore: -------------------------------------------------------------------------------- 1 | # Empty directory 2 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. _authors: 2 | .. include:: ../AUTHORS.rst 3 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # This file is execfile()d with the current directory set to its containing dir. 4 | # 5 | # Note that not all possible configuration values are present in this 6 | # autogenerated file. 7 | # 8 | # All configuration values have a default; values that are commented out 9 | # serve to show the default. 10 | 11 | import os 12 | import sys 13 | import inspect 14 | import shutil 15 | 16 | __location__ = os.path.join(os.getcwd(), os.path.dirname( 17 | inspect.getfile(inspect.currentframe()))) 18 | 19 | # If extensions (or modules to document with autodoc) are in another directory, 20 | # add these directories to sys.path here. If the directory is relative to the 21 | # documentation root, use os.path.abspath to make it absolute, like shown here. 22 | sys.path.insert(0, os.path.join(__location__, '../src')) 23 | 24 | # -- Run sphinx-apidoc ------------------------------------------------------ 25 | # This hack is necessary since RTD does not issue `sphinx-apidoc` before running 26 | # `sphinx-build -b html . _build/html`. See Issue: 27 | # https://github.com/rtfd/readthedocs.org/issues/1139 28 | # DON'T FORGET: Check the box "Install your project inside a virtualenv using 29 | # setup.py install" in the RTD Advanced Settings. 30 | # Additionally it helps us to avoid running apidoc manually 31 | 32 | try: # for Sphinx >= 1.7 33 | from sphinx.ext import apidoc 34 | except ImportError: 35 | from sphinx import apidoc 36 | 37 | output_dir = os.path.join(__location__, "api") 38 | module_dir = os.path.join(__location__, "../src/tweetscap") 39 | try: 40 | shutil.rmtree(output_dir) 41 | except FileNotFoundError: 42 | pass 43 | 44 | try: 45 | import sphinx 46 | from distutils.version import LooseVersion 47 | 48 | cmd_line_template = "sphinx-apidoc -f -o {outputdir} {moduledir}" 49 | cmd_line = cmd_line_template.format(outputdir=output_dir, moduledir=module_dir) 50 | 51 | args = cmd_line.split(" ") 52 | if LooseVersion(sphinx.__version__) >= LooseVersion('1.7'): 53 | args = args[1:] 54 | 55 | apidoc.main(args) 56 | except Exception as e: 57 | print("Running `sphinx-apidoc` failed!\n{}".format(e)) 58 | 59 | # -- General configuration ----------------------------------------------------- 60 | 61 | # If your documentation needs a minimal Sphinx version, state it here. 62 | # needs_sphinx = '1.0' 63 | 64 | # Add any Sphinx extension module names here, as strings. They can be extensions 65 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 66 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 67 | 'sphinx.ext.autosummary', 'sphinx.ext.viewcode', 'sphinx.ext.coverage', 68 | 'sphinx.ext.doctest', 'sphinx.ext.ifconfig', 'sphinx.ext.mathjax', 69 | 'sphinx.ext.napoleon'] 70 | 71 | # Add any paths that contain templates here, relative to this directory. 72 | templates_path = ['_templates'] 73 | 74 | # The suffix of source filenames. 75 | source_suffix = '.rst' 76 | 77 | # The encoding of source files. 78 | # source_encoding = 'utf-8-sig' 79 | 80 | # The master toctree document. 81 | master_doc = 'index' 82 | 83 | # General information about the project. 84 | project = u'tweet_scrapper' 85 | copyright = u'2018, 5hirishk' 86 | 87 | # The version info for the project you're documenting, acts as replacement for 88 | # |version| and |release|, also used in various other places throughout the 89 | # built documents. 90 | # 91 | # The short X.Y version. 92 | version = '' # Is set by calling `setup.py docs` 93 | # The full version, including alpha/beta/rc tags. 94 | release = '' # Is set by calling `setup.py docs` 95 | 96 | # The language for content autogenerated by Sphinx. Refer to documentation 97 | # for a list of supported languages. 98 | # language = None 99 | 100 | # There are two options for replacing |today|: either, you set today to some 101 | # non-false value, then it is used: 102 | # today = '' 103 | # Else, today_fmt is used as the format for a strftime call. 104 | # today_fmt = '%B %d, %Y' 105 | 106 | # List of patterns, relative to source directory, that match files and 107 | # directories to ignore when looking for source files. 108 | exclude_patterns = ['_build'] 109 | 110 | # The reST default role (used for this markup: `text`) to use for all documents. 111 | # default_role = None 112 | 113 | # If true, '()' will be appended to :func: etc. cross-reference text. 114 | # add_function_parentheses = True 115 | 116 | # If true, the current module name will be prepended to all description 117 | # unit titles (such as .. function::). 118 | # add_module_names = True 119 | 120 | # If true, sectionauthor and moduleauthor directives will be shown in the 121 | # output. They are ignored by default. 122 | # show_authors = False 123 | 124 | # The name of the Pygments (syntax highlighting) style to use. 125 | pygments_style = 'sphinx' 126 | 127 | # A list of ignored prefixes for module index sorting. 128 | # modindex_common_prefix = [] 129 | 130 | # If true, keep warnings as "system message" paragraphs in the built documents. 131 | # keep_warnings = False 132 | 133 | 134 | # -- Options for HTML output --------------------------------------------------- 135 | 136 | # The theme to use for HTML and HTML Help pages. See the documentation for 137 | # a list of builtin themes. 138 | html_theme = 'alabaster' 139 | 140 | # Theme options are theme-specific and customize the look and feel of a theme 141 | # further. For a list of options available for each theme, see the 142 | # documentation. 143 | # html_theme_options = {} 144 | 145 | # Add any paths that contain custom themes here, relative to this directory. 146 | # html_theme_path = [] 147 | 148 | # The name for this set of Sphinx documents. If None, it defaults to 149 | # " v documentation". 150 | try: 151 | from tweetscap import __version__ as version 152 | except ImportError: 153 | pass 154 | else: 155 | release = version 156 | 157 | # A shorter title for the navigation bar. Default is the same as html_title. 158 | # html_short_title = None 159 | 160 | # The name of an image file (relative to this directory) to place at the top 161 | # of the sidebar. 162 | # html_logo = "" 163 | 164 | # The name of an image file (within the static path) to use as favicon of the 165 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 166 | # pixels large. 167 | # html_favicon = None 168 | 169 | # Add any paths that contain custom static files (such as style sheets) here, 170 | # relative to this directory. They are copied after the builtin static files, 171 | # so a file named "default.css" will overwrite the builtin "default.css". 172 | html_static_path = ['_static'] 173 | 174 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 175 | # using the given strftime format. 176 | # html_last_updated_fmt = '%b %d, %Y' 177 | 178 | # If true, SmartyPants will be used to convert quotes and dashes to 179 | # typographically correct entities. 180 | # html_use_smartypants = True 181 | 182 | # Custom sidebar templates, maps document names to template names. 183 | # html_sidebars = {} 184 | 185 | # Additional templates that should be rendered to pages, maps page names to 186 | # template names. 187 | # html_additional_pages = {} 188 | 189 | # If false, no module index is generated. 190 | # html_domain_indices = True 191 | 192 | # If false, no index is generated. 193 | # html_use_index = True 194 | 195 | # If true, the index is split into individual pages for each letter. 196 | # html_split_index = False 197 | 198 | # If true, links to the reST sources are added to the pages. 199 | # html_show_sourcelink = True 200 | 201 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 202 | # html_show_sphinx = True 203 | 204 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 205 | # html_show_copyright = True 206 | 207 | # If true, an OpenSearch description file will be output, and all pages will 208 | # contain a tag referring to it. The value of this option must be the 209 | # base URL from which the finished HTML is served. 210 | # html_use_opensearch = '' 211 | 212 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 213 | # html_file_suffix = None 214 | 215 | # Output file base name for HTML help builder. 216 | htmlhelp_basename = 'tweetscap-doc' 217 | 218 | 219 | # -- Options for LaTeX output -------------------------------------------------- 220 | 221 | latex_elements = { 222 | # The paper size ('letterpaper' or 'a4paper'). 223 | # 'papersize': 'letterpaper', 224 | 225 | # The font size ('10pt', '11pt' or '12pt'). 226 | # 'pointsize': '10pt', 227 | 228 | # Additional stuff for the LaTeX preamble. 229 | # 'preamble': '', 230 | } 231 | 232 | # Grouping the document tree into LaTeX files. List of tuples 233 | # (source start file, target name, title, author, documentclass [howto/manual]). 234 | latex_documents = [ 235 | ('index', 'user_guide.tex', u'tweet_scrapper Documentation', 236 | u'5hirishk', 'manual'), 237 | ] 238 | 239 | # The name of an image file (relative to this directory) to place at the top of 240 | # the title page. 241 | # latex_logo = "" 242 | 243 | # For "manual" documents, if this is true, then toplevel headings are parts, 244 | # not chapters. 245 | # latex_use_parts = False 246 | 247 | # If true, show page references after internal links. 248 | # latex_show_pagerefs = False 249 | 250 | # If true, show URL addresses after external links. 251 | # latex_show_urls = False 252 | 253 | # Documents to append as an appendix to all manuals. 254 | # latex_appendices = [] 255 | 256 | # If false, no module index is generated. 257 | # latex_domain_indices = True 258 | 259 | # -- External mapping ------------------------------------------------------------ 260 | python_version = '.'.join(map(str, sys.version_info[0:2])) 261 | intersphinx_mapping = { 262 | 'sphinx': ('http://www.sphinx-doc.org/en/stable', None), 263 | 'python': ('https://docs.python.org/' + python_version, None), 264 | 'matplotlib': ('https://matplotlib.org', None), 265 | 'numpy': ('https://docs.scipy.org/doc/numpy', None), 266 | 'sklearn': ('http://scikit-learn.org/stable', None), 267 | 'pandas': ('http://pandas.pydata.org/pandas-docs/stable', None), 268 | 'scipy': ('https://docs.scipy.org/doc/scipy/reference', None), 269 | } 270 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | ============== 2 | tweet_scrapper 3 | ============== 4 | 5 | This is the documentation of **tweet_scrapper**. 6 | 7 | .. note:: 8 | 9 | This is the main page of your project's `Sphinx `_ 10 | documentation. It is formatted in `reStructuredText 11 | `__. Add additional pages by creating 12 | rst-files in ``docs`` and adding them to the `toctree 13 | `_ below. Use then 14 | `references `__ in order to link 15 | them from this page, e.g. :ref:`authors ` and :ref:`changes`. 16 | 17 | It is also possible to refer to the documentation of other Python packages 18 | with the `Python domain syntax 19 | `__. By default you 20 | can reference the documentation of `Sphinx `__, 21 | `Python `__, `NumPy 22 | `__, `SciPy 23 | `__, `matplotlib 24 | `__, `Pandas 25 | `__, `Scikit-Learn 26 | `__. You can add more by 27 | extending the ``intersphinx_mapping`` in your Sphinx's ``conf.py``. 28 | 29 | The pretty useful extension `autodoc 30 | `__ is activated by 31 | default and lets you include documentation from docstrings. Docstrings can 32 | be written in `Google 33 | `__ 34 | (recommended!), `NumPy 35 | `__ 36 | and `classical 37 | `__ 38 | style. 39 | 40 | 41 | Contents 42 | ======== 43 | 44 | .. toctree:: 45 | :maxdepth: 2 46 | 47 | License 48 | Authors 49 | Changelog 50 | Module Reference 51 | 52 | 53 | Indices and tables 54 | ================== 55 | 56 | * :ref:`genindex` 57 | * :ref:`modindex` 58 | * :ref:`search` 59 | -------------------------------------------------------------------------------- /docs/license.rst: -------------------------------------------------------------------------------- 1 | .. _license: 2 | 3 | ======= 4 | License 5 | ======= 6 | 7 | .. literalinclude:: ../LICENSE.txt 8 | -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | # Add requirements only needed for your unittests and during development here. 2 | # They will be installed automatically when running `python setup.py test`. 3 | # ATTENTION: Don't remove pytest-cov and pytest as they are needed. 4 | pytest 5 | pytest-cov==2.5.0 6 | codecov -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | lxml>=4.1.0 2 | requests>=2.18.0 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Note: To use the 'upload' functionality of this file, you must: 5 | # $ pipenv install twine --dev 6 | 7 | import io 8 | import os 9 | import sys 10 | from shutil import rmtree 11 | 12 | from setuptools import find_packages, setup, Command 13 | 14 | # Package meta-data. 15 | NAME = 'tweetscrape' 16 | DESCRIPTION = 'Scrape the Twitter frontend API without any authentication and restriction.' 17 | URL = 'https://github.com/5hirish/tweet_scrapper' 18 | EMAIL = 'shirishkadam35@gmail.com' 19 | AUTHOR = 'Shirish Kadam' 20 | REQUIRES_PYTHON = '>=3.5.*' 21 | VERSION = '0.6.2' 22 | LICENSE = 'gpl3' 23 | 24 | PACKAGES = ['tweetscrape'] 25 | EXCLUDE = ["tests", "*.tests", "*.tests.*", "tests.*"] 26 | 27 | CLASSIFIERS = [ 28 | # Trove classifiers 29 | # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers 30 | 'Development Status :: 5 - Production/Stable', 31 | 'Intended Audience :: Education', 32 | 'Intended Audience :: Developers', 33 | 'Intended Audience :: Science/Research', 34 | 'Operating System :: OS Independent', 35 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 36 | 'Programming Language :: Python', 37 | 'Programming Language :: Python :: 3', 38 | 'Programming Language :: Python :: 3.5', 39 | 'Programming Language :: Python :: 3.6', 40 | 'Topic :: Software Development :: Libraries :: Python Modules', 41 | 'Topic :: Scientific/Engineering', 42 | 'Topic :: Scientific/Engineering :: Information Analysis' 43 | ] 44 | # What packages are required for this module to be executed? 45 | REQUIRED = [ 46 | 'lxml', 'requests', 47 | ] 48 | 49 | # What packages are optional? 50 | EXTRAS = { 51 | # 'fancy feature': ['django'], 52 | } 53 | 54 | # The rest you shouldn't have to touch too much :) 55 | # ------------------------------------------------ 56 | # Except, perhaps the License and Trove Classifiers! 57 | # If you do change the License, remember to change the Trove Classifier for that! 58 | 59 | here = os.path.abspath(os.path.dirname(__file__)) 60 | 61 | # Import the README and use it as the long-description. 62 | # Note: this will only work if 'README.md' is present in your MANIFEST.in file! 63 | try: 64 | with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f: 65 | long_description = '\n' + f.read() 66 | except FileNotFoundError: 67 | long_description = DESCRIPTION 68 | 69 | # Load the package's __version__.py module as a dictionary. 70 | about = {} 71 | if not VERSION: 72 | project_slug = NAME.lower().replace("-", "_").replace(" ", "_") 73 | with open(os.path.join(here, project_slug, '__version__.py')) as f: 74 | exec(f.read(), about) 75 | else: 76 | about['__version__'] = VERSION 77 | 78 | 79 | class UploadCommand(Command): 80 | """Support setup.py upload.""" 81 | 82 | description = 'Build and publish the package.' 83 | user_options = [] 84 | 85 | @staticmethod 86 | def status(s): 87 | """Prints things in bold.""" 88 | print('\033[1m{0}\033[0m'.format(s)) 89 | 90 | def initialize_options(self): 91 | pass 92 | 93 | def finalize_options(self): 94 | pass 95 | 96 | def run(self): 97 | try: 98 | self.status('Removing previous builds…') 99 | rmtree(os.path.join(here, 'dist')) 100 | except OSError: 101 | pass 102 | 103 | self.status('Building Source and Wheel (universal) distribution…') 104 | os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) 105 | 106 | self.status('Uploading the package to PyPI via Twine…') 107 | os.system('twine upload dist/*') 108 | 109 | self.status('Pushing git tags…') 110 | os.system('git tag v{0}'.format(about['__version__'])) 111 | os.system('git push --tags') 112 | 113 | sys.exit() 114 | 115 | 116 | # Where the magic happens: 117 | setup( 118 | name=NAME, 119 | version=about['__version__'], 120 | description=DESCRIPTION, 121 | long_description=long_description, 122 | long_description_content_type='text/markdown', 123 | author=AUTHOR, 124 | author_email=EMAIL, 125 | python_requires=REQUIRES_PYTHON, 126 | url=URL, 127 | packages=find_packages(exclude=EXCLUDE), 128 | # If your package is a single module, use this instead of 'packages': 129 | # py_modules=PACKAGES, 130 | 131 | # entry_points={ 132 | # 'console_scripts': ['mycli=mymodule:cli'], 133 | # }, 134 | install_requires=REQUIRED, 135 | extras_require=EXTRAS, 136 | include_package_data=True, 137 | license=LICENSE, 138 | classifiers=CLASSIFIERS, 139 | # $ setup.py publish support. 140 | cmdclass={ 141 | 'upload': UploadCommand, 142 | }, 143 | ) -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/tweet_scrapper/4337e09aae8d82cdd0f63d5ec9978e0aa0a1a571/tests/__init__.py -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Dummy conftest.py for tweetscap. 4 | 5 | If you don't know what this is for, just leave it empty. 6 | Read more about conftest.py under: 7 | https://pytest.org/latest/plugins.html 8 | """ 9 | -------------------------------------------------------------------------------- /tests/test_conversation_tweets.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import os 3 | import csv 4 | from tweetscrape.conversation_tweets import TweetScrapperConversation 5 | 6 | 7 | @pytest.mark.parametrize("test_user,test_tweet,test_page", [ 8 | ("naval", 1142596407460634624, 40), 9 | ("ewarren", 1146415363460141057, 30), 10 | ("ChrisEvans", 1138806658912702464, 100) 11 | ]) 12 | def test_user_tweets(test_user, test_tweet, test_page): 13 | ts = TweetScrapperConversation(test_user, test_tweet, test_page, 'twitter.csv', 'csv') 14 | tweet_count, tweet_id, tweet_time, dump_path = ts.get_thread_tweets(False) 15 | 16 | assert os.path.exists(dump_path) 17 | 18 | if test_page > 0: 19 | assert tweet_count > 20 20 | 21 | with open(dump_path, 'r') as csv_fp: 22 | csv_reader = csv.DictReader(csv_fp) 23 | for tweets in csv_reader: 24 | assert tweets.get('id') is not None 25 | assert tweets.get('text') is not None 26 | assert tweets.get('time') is not None 27 | 28 | os.remove(dump_path) -------------------------------------------------------------------------------- /tests/test_profile_tweets.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import os 3 | import csv 4 | from tweetscrape.profile_tweets import TweetScrapperProfile 5 | 6 | 7 | @pytest.mark.parametrize("test_user,test_page", [ 8 | ("@BarackObama", 40), 9 | ("@fchollet", 120), 10 | ("@Kasparov63", 20), 11 | ("@ShashiTharoor", 200), 12 | # ("@EdwardSnowden", 15), 13 | # ("@colbertlateshow", 5), 14 | # ("@HamillHimself", 4) 15 | 16 | ]) 17 | def test_user_tweets(test_user, test_page): 18 | ts = TweetScrapperProfile(test_user, test_page, 'twitter.csv', 'csv') 19 | tweet_count, tweet_id, tweet_time, dump_path = ts.get_profile_tweets(False) 20 | 21 | assert os.path.exists(dump_path) 22 | 23 | if test_page > 0: 24 | assert tweet_count == pytest.approx(test_page, abs=5) 25 | 26 | with open(dump_path, 'r') as csv_fp: 27 | csv_reader = csv.DictReader(csv_fp) 28 | for tweets in csv_reader: 29 | assert tweets.get('id') is not None 30 | assert tweets.get('text') is not None 31 | assert tweets.get('time') is not None 32 | 33 | os.remove(dump_path) -------------------------------------------------------------------------------- /tests/test_search_tweets.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import os 3 | import csv 4 | import ast 5 | from datetime import datetime 6 | from tweetscrape.search_tweets import TweetScrapperSearch 7 | 8 | 9 | @pytest.mark.parametrize("test_term,test_page", [ 10 | ("New York", 40), 11 | ("White House", 60), 12 | ("Avengers Infinity War", 100), 13 | # ("Machine Learning", 10), 14 | # ("The Rock", 15) 15 | ]) 16 | def test_search_tweets(test_term, test_page): 17 | 18 | ts = TweetScrapperSearch(search_all=test_term, 19 | num_tweets=test_page, 20 | tweet_dump_path='twitter.csv', 21 | tweet_dump_format='csv') 22 | 23 | tweet_count, tweet_id, last_time, dump_path = ts.get_search_tweets() 24 | 25 | assert os.path.exists(dump_path) 26 | 27 | # assert tweet_count > (test_page - 1) * 20 28 | assert tweet_count >= 5 29 | 30 | with open(dump_path, 'r') as csv_fp: 31 | csv_reader = csv.DictReader(csv_fp) 32 | for tweets in csv_reader: 33 | assert tweets.get('id') is not None 34 | assert tweets.get('text') is not None 35 | assert tweets.get('time') is not None 36 | 37 | os.remove(dump_path) 38 | 39 | 40 | @pytest.mark.parametrize("test_tag,test_page", [ 41 | ("#StarWars", 60), 42 | ("#FakeNews", 120), 43 | # ("#Hamilton", 5), 44 | # ("#MarchForOurLives", 1), 45 | # ("#CNN", 12) 46 | ]) 47 | def test_hashtag_tweets(test_tag, test_page): 48 | 49 | ts = TweetScrapperSearch(search_hashtags=test_tag, 50 | num_tweets=test_page, 51 | tweet_dump_path='twitter.csv', 52 | tweet_dump_format='csv') 53 | 54 | tweet_count, tweet_id, last_time, dump_path = ts.get_search_tweets() 55 | 56 | assert os.path.exists(dump_path) 57 | 58 | # assert tweet_count >= (test_page - 1) * 20 59 | assert tweet_count >= 5 60 | 61 | with open(dump_path, 'r') as csv_fp: 62 | csv_reader = csv.DictReader(csv_fp) 63 | for tweets in csv_reader: 64 | assert tweets.get('id') is not None 65 | assert tweets.get('text') is not None 66 | assert tweets.get('time') is not None 67 | assert tweets.get('hashtags') is not None 68 | assert len(ast.literal_eval(tweets.get('hashtags'))) > 0 69 | # extracted_hastags = [ht.lower() for ht in ast.literal_eval(tweets.get('hashtags'))] 70 | # assert test_tag.lower() in extracted_hastags 71 | 72 | os.remove(dump_path) 73 | 74 | 75 | @pytest.mark.parametrize("test_until,test_since,test_from,test_page", [ 76 | # ("2019-03-01", "2019-01-01", "@BarackObama", 100), 77 | ("2016-04-01", "2015-11-01", "@CNN", 40), 78 | ("2017-08-01", "2017-07-01", "@BBC", 40), 79 | ("2012-01-01", "2011-12-20", "@ABC", 40) 80 | ]) 81 | def test_time_interval_tweets(test_until, test_since, test_from, test_page): 82 | ts = TweetScrapperSearch(search_from_accounts=test_from, 83 | search_till_date=test_until, 84 | search_since_date=test_since, 85 | num_tweets=test_page, 86 | tweet_dump_path='twitter.csv', 87 | tweet_dump_format='csv') 88 | 89 | tweet_count, tweet_id, last_time, dump_path = ts.get_search_tweets() 90 | 91 | since_timestamp = datetime.strptime(test_since, '%Y-%m-%d').timestamp() 92 | until_timestamp = datetime.strptime(test_until, '%Y-%m-%d').timestamp() 93 | 94 | assert os.path.exists(dump_path) 95 | 96 | assert tweet_count == pytest.approx(test_page, abs=5) 97 | 98 | with open(dump_path, 'r') as csv_fp: 99 | csv_reader = csv.DictReader(csv_fp) 100 | for tweets in csv_reader: 101 | assert tweets.get('id') is not None 102 | assert tweets.get('text') is not None 103 | assert tweets.get('time') is not None 104 | # tweet_time = int(tweets.get('time')) / 1000 105 | # assert until_timestamp >= tweet_time >= since_timestamp 106 | 107 | os.remove(dump_path) -------------------------------------------------------------------------------- /tests/test_users_scrape.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from tweetscrape.users_scrape import TweetScrapperUser 3 | 4 | 5 | @pytest.mark.parametrize("test_user", [ 6 | ("naval"), 7 | ("ewarren"), 8 | ("ChrisEvans") 9 | ]) 10 | def test_user_tweets(test_user): 11 | ts = TweetScrapperUser(test_user) 12 | user_info = ts.get_profile_info(False) 13 | 14 | assert user_info.get("name") is not None 15 | assert user_info.get("tweets") is not None 16 | assert user_info.get("following") is not None 17 | assert user_info.get("followers") is not None 18 | # assert user_info.get("favorites") is not None 19 | -------------------------------------------------------------------------------- /tweetscrape/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from pkg_resources import get_distribution, DistributionNotFound 3 | 4 | try: 5 | # Change here if project is renamed and does not equal the package name 6 | dist_name = 'tweetscrape' 7 | __version__ = get_distribution(dist_name).version 8 | except DistributionNotFound: 9 | __version__ = 'unknown' 10 | -------------------------------------------------------------------------------- /tweetscrape/conversation_tweets.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from math import ceil 3 | 4 | from tweetscrape.tweets_scrape import TweetScrapper 5 | 6 | """ 7 | Parsing with XPath 1.0 query 8 | XPath Documentation : https://developer.mozilla.org/en-US/docs/Web/XPath 9 | The '.' at the beginning means, that the current processing starts at the current node. 10 | Your xpath starts with a slash '/' and is therefore absolute. 11 | The '*' selects all element nodes descending from this current node with the @id-attribute-value or @class value'. 12 | The '//' identifies any descendant designation element of element 13 | """ 14 | 15 | logger = logging.getLogger(__name__) 16 | 17 | 18 | class TweetScrapperConversation(TweetScrapper): 19 | username = "5hirish" 20 | pages = 0 21 | 22 | def __init__(self, username, parent_tweet_id, num_tweets=40, 23 | tweet_dump_path="", tweet_dump_format="", 24 | request_proxies=None): 25 | self.username = username 26 | self.parent_tweet_id = parent_tweet_id 27 | 28 | if num_tweets > 0: 29 | self.pages = ceil(num_tweets / 20) 30 | else: 31 | self.pages = -1 32 | 33 | self.__twitter_init_conversation_url__ = 'https://twitter.com/{username}/status/{parent_tweet_id}' \ 34 | .format(username=self.username, parent_tweet_id=self.parent_tweet_id) 35 | 36 | self.__twitter_init_conversation_params__ = { 37 | 'conversation_id': self.parent_tweet_id 38 | } 39 | 40 | self.__twitter_conversation_params__ = { 41 | 'include_available_features': 1, 42 | 'include_entities': 1 43 | } 44 | 45 | self.__twitter_conversation_header__ = { 46 | 'referer': 'https://twitter.com/{username}/status/{parent_tweet_id}' 47 | .format(username=self.username, parent_tweet_id=self.parent_tweet_id) 48 | } 49 | 50 | super().__init__(self.__twitter_init_conversation_url__, 51 | self.__twitter_conversation_header__, 52 | self.__twitter_init_conversation_params__, 53 | request_proxies, 54 | self.pages, tweet_dump_path, tweet_dump_format) 55 | 56 | def get_thread_tweets(self, save_output=False): 57 | output_file_name = '/' + self.username + '_conversation' 58 | # Search Profile since: until: from: 59 | # conversation_id 60 | if self.username is not None and self.username != "": 61 | self.username = self.username.replace("@", "") 62 | tweet_count, last_tweet_id, last_tweet_time, dump_path = \ 63 | self.execute_twitter_request(username=self.username, 64 | conversation_id=self.parent_tweet_id, 65 | log_output=save_output, 66 | log_file=output_file_name) 67 | 68 | # if self.pages == -1 or (self.pages - 1 * 20) > tweet_count: 69 | # logger.info("Switching to search mode. Profile Limit exhausted") 70 | # ts = TweetScrapperSearch(search_from_accounts=self.username, 71 | # search_since_date=TweetScrapperSearch.twitter_from_date, 72 | # search_till_date=last_tweet_time) 73 | # append_tweet_count, last_tweet_id, last_tweet_time, dump_path = ts.get_search_tweets(save_output) 74 | # tweet_count += append_tweet_count 75 | 76 | return tweet_count, last_tweet_id, last_tweet_time, dump_path 77 | return 0, 0, 0, output_file_name 78 | 79 | 80 | if __name__ == '__main__': 81 | logging.basicConfig(level=logging.DEBUG) 82 | # https://twitter.com/ewarren/status/1146132929065738246?conversation_id=1146132929065738246 83 | l_ts = TweetScrapperConversation("ewarren", 1146415363460141057, 40, 'twitter_conv.csv', 'csv') 84 | l_tweet_count, l_tweet_id, l_tweet_time, l_dump_path = l_ts.get_thread_tweets(True) 85 | # for l_tweet in l_extracted_tweets: 86 | # print(str(l_tweet)) 87 | print(l_tweet_count) 88 | -------------------------------------------------------------------------------- /tweetscrape/model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/5hirish/tweet_scrapper/4337e09aae8d82cdd0f63d5ec9978e0aa0a1a571/tweetscrape/model/__init__.py -------------------------------------------------------------------------------- /tweetscrape/model/tweet_model.py: -------------------------------------------------------------------------------- 1 | 2 | class TweetInfo: 3 | __tweet_id__ = -1 4 | __tweet_type__ = None 5 | __tweet_author__ = None 6 | __tweet_author_name__ = None 7 | __tweet_author_id__ = None 8 | __tweet_is_retweet__ = False 9 | __tweet_has_parent__ = False 10 | __tweet_conversation_id__ = None 11 | __tweet_retweetwer__ = None 12 | __tweet_text__ = None 13 | __tweet_time_ms__ = 0 14 | __tweet_links__ = [] 15 | __tweet_hashtags__ = [] 16 | __tweet_mentions__ = [] 17 | __tweet_replies_count__ = 0 18 | __tweet_favorite_count__ = 0 19 | __tweet_retweet_count__ = 0 20 | 21 | tweet_fields = ["id", "type", "time", "author", "author_id", "re_tweeter", "associated_tweet", 22 | "text", "links", "hashtags", "mentions", "reply_count", "favorite_count", "retweet_count"] 23 | 24 | def __init__(self, tweet_id, tweet_type): 25 | self.__tweet_id__ = tweet_id 26 | self.__tweet_type__ = tweet_type 27 | self.__tweet_links__ = [] 28 | self.__tweet_hashtags__ = [] 29 | self.__tweet_mentions__ = [] 30 | 31 | def get_tweet_id(self): 32 | return self.__tweet_id__ 33 | 34 | def get_tweet_type(self): 35 | return self.__tweet_type__ 36 | 37 | def set_tweet_author(self, tweet_author, tweet_author_name, tweet_author_id): 38 | self.__tweet_author__ = tweet_author 39 | self.__tweet_author_name__ = tweet_author_name 40 | self.__tweet_author_id__ = tweet_author_id 41 | 42 | def get_tweet_author(self): 43 | return self.__tweet_author__ 44 | 45 | def get_tweet_author_name(self): 46 | return self.__tweet_author_name__ 47 | 48 | def get_tweet_author_id(self): 49 | return self.__tweet_author_id__ 50 | 51 | def set_retweeter(self, retweeter): 52 | self.__tweet_retweetwer__ = retweeter 53 | self.__tweet_is_retweet__ = True 54 | 55 | def get_retweeter(self): 56 | return self.__tweet_retweetwer__ 57 | 58 | def get_is_retweeter(self): 59 | return self.__tweet_is_retweet__ 60 | 61 | def set_tweet_conversation(self, tweet_conversation_id, tweet_has_parent): 62 | self.__tweet_conversation_id__ = tweet_conversation_id 63 | self.__tweet_has_parent__ = tweet_has_parent 64 | 65 | def get_conversation_id(self): 66 | return self.__tweet_conversation_id__ 67 | 68 | def get_has_parent(self): 69 | return self.__tweet_has_parent__ 70 | 71 | def set_tweet_text(self, tweet_text): 72 | self.__tweet_text__ = tweet_text 73 | 74 | def get_tweet_text(self): 75 | return self.__tweet_text__ 76 | 77 | def set_tweet_time_ms(self, tweet_time_ms): 78 | self.__tweet_time_ms__ = tweet_time_ms 79 | 80 | def get_tweet_time_ms(self): 81 | return self.__tweet_time_ms__ 82 | 83 | def set_tweet_links(self, tweet_link): 84 | self.__tweet_links__.append(tweet_link) 85 | 86 | def get_tweet_links(self): 87 | return self.__tweet_links__ 88 | 89 | def set_tweet_hashtags(self, tweet_hashtag): 90 | self.__tweet_hashtags__.append(tweet_hashtag) 91 | 92 | def get_tweet_hashtags(self): 93 | return self.__tweet_hashtags__ 94 | 95 | def set_tweet_mentions(self, tweet_mention): 96 | self.__tweet_mentions__.append(tweet_mention) 97 | 98 | def get_tweet_mentions(self): 99 | return self.__tweet_mentions__ 100 | 101 | def set_tweet_interactions(self, tweet_replies_count, tweet_favorite_count, tweet_retweet_count): 102 | self.__tweet_replies_count__ = tweet_replies_count 103 | self.__tweet_favorite_count__ = tweet_favorite_count 104 | self.__tweet_retweet_count__ = tweet_retweet_count 105 | 106 | def get_tweet_replies_count(self): 107 | return self.__tweet_replies_count__ 108 | 109 | def get_tweet_favorite_count(self): 110 | return self.__tweet_favorite_count__ 111 | 112 | def get_tweet_retweet_count(self): 113 | return self.__tweet_retweet_count__ 114 | 115 | def get_json(self): 116 | return { 117 | "id": self.get_tweet_id(), 118 | "type": self.get_tweet_type(), 119 | "time": self.get_tweet_time_ms(), 120 | "author": self.get_tweet_author(), 121 | "author_id": self.get_tweet_author_id(), 122 | "re_tweeter": self.get_retweeter(), 123 | "associated_tweet": self.get_conversation_id(), 124 | "text": self.get_tweet_text(), 125 | "links": self.get_tweet_links(), 126 | "hashtags": self.get_tweet_hashtags(), 127 | "mentions": self.get_tweet_mentions(), 128 | "reply_count": self.get_tweet_replies_count(), 129 | "favorite_count": self.get_tweet_favorite_count(), 130 | "retweet_count": self.get_tweet_retweet_count() 131 | } 132 | 133 | def __str__(self): 134 | return "Id: " + self.get_tweet_id() + "\tType: " + self.get_tweet_type() + "\tTime: " + self.get_tweet_time_ms() + \ 135 | "\nAuthor: " + self.get_tweet_author() + "\tAuthorId: " + self.get_tweet_author_id() + \ 136 | "\nReTweeter: " + str(self.get_retweeter()) + \ 137 | "\nAssociated Tweet: " + str(self.get_conversation_id()) + \ 138 | "\nText: " + self.get_tweet_text() + \ 139 | "\nLinks: " + str(self.get_tweet_links()) + \ 140 | "\nHashtags: " + str(self.get_tweet_hashtags()) + \ 141 | "\nMentions: " + str(self.get_tweet_mentions()) + \ 142 | "\nReplies: " + self.get_tweet_replies_count() + \ 143 | "\tFavorites: " + self.get_tweet_favorite_count() + \ 144 | "\tRetweets: " + self.get_tweet_retweet_count() + "\n" 145 | -------------------------------------------------------------------------------- /tweetscrape/model/user_model.py: -------------------------------------------------------------------------------- 1 | 2 | class UserInfo: 3 | __user_handle__ = None 4 | __user_name__ = None 5 | __user_bio__ = None 6 | __user_location__ = None 7 | __user_location_id__ = None 8 | __user_url__ = None 9 | __user_tweets__ = 0 10 | __user_following__ = 0 11 | __user_followers__ = 0 12 | __user_favorites__ = 0 13 | 14 | def __init__(self, user_handle, user_name, user_bio, user_location, user_location_id, 15 | user_url, user_tweets, user_following, user_followers, user_favorites): 16 | self.__user_handle__ = user_handle 17 | self.__user_name__ = user_name 18 | self.__user_bio__ = user_bio 19 | self.__user_location__ = user_location 20 | self.__user_location_id__ = user_location_id 21 | self.__user_url__ = user_url 22 | self.__user_tweets__ = user_tweets 23 | self.__user_following__ = user_following 24 | self.__user_followers__ = user_followers 25 | self.__user_favorites__ = user_favorites 26 | 27 | def get_user_handle(self): 28 | return self.__user_handle__ 29 | 30 | def get_user_name(self): 31 | return self.__user_name__ 32 | 33 | def get_json(self): 34 | return { 35 | "username": self.__user_handle__, 36 | "name": self.__user_name__, 37 | "bio": self.__user_bio__, 38 | "location": self.__user_location__, 39 | "location_id": self.__user_location_id__, 40 | "url": self.__user_url__, 41 | "tweets": self.__user_tweets__, 42 | "following": self.__user_following__, 43 | "followers": self.__user_followers__, 44 | "favorites": self.__user_favorites__ 45 | } 46 | -------------------------------------------------------------------------------- /tweetscrape/profile_tweets.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from math import ceil 3 | 4 | from tweetscrape.tweets_scrape import TweetScrapper 5 | from tweetscrape.search_tweets import TweetScrapperSearch 6 | 7 | """ 8 | Parsing with XPath 1.0 query 9 | XPath Documentation : https://developer.mozilla.org/en-US/docs/Web/XPath 10 | The '.' at the beginning means, that the current processing starts at the current node. 11 | Your xpath starts with a slash '/' and is therefore absolute. 12 | The '*' selects all element nodes descending from this current node with the @id-attribute-value or @class value'. 13 | The '//' identifies any descendant designation element of element 14 | """ 15 | 16 | logger = logging.getLogger(__name__) 17 | 18 | 19 | class TweetScrapperProfile(TweetScrapper): 20 | username = "5hirish" 21 | pages = 0 22 | 23 | __twitter_profile_url__ = None 24 | __twitter_profile_header__ = None 25 | __twitter_profile_params__ = None 26 | 27 | def __init__(self, username, num_tweets=40, 28 | tweet_dump_path="", tweet_dump_format="", 29 | request_proxies=None): 30 | self.username = username 31 | 32 | if num_tweets > 0: 33 | self.pages = ceil(num_tweets/20) 34 | else: 35 | self.pages = -1 36 | 37 | self.__twitter_profile_timeline_url__ = 'https://twitter.com/i/profiles/show/{username}/timeline/tweets' \ 38 | .format(username=self.username) 39 | 40 | self.__twitter_profile_params__ = { 41 | 'include_available_features': 1, 42 | 'include_entities': 1, 43 | 'include_new_items_bar': True 44 | } 45 | 46 | self.__twitter_profile_header__ = { 47 | 'referer': 'https://twitter.com/{username}'.format(username=self.username) 48 | } 49 | 50 | super().__init__(self.__twitter_profile_timeline_url__, 51 | self.__twitter_profile_header__, 52 | self.__twitter_profile_params__, 53 | request_proxies, 54 | self.pages, tweet_dump_path, tweet_dump_format) 55 | 56 | def get_profile_tweets(self, save_output=False): 57 | output_file_name = '/' + self.username + '_profile' 58 | # Search Profile since: until: from: 59 | if self.username is not None and self.username != "": 60 | # self.update_request_url(self.__twitter_profile_timeline_url__) 61 | self.username = self.username.replace("@", "") 62 | tweet_count, last_tweet_id, last_tweet_time, dump_path = \ 63 | self.execute_twitter_request(username=self.username, 64 | log_output=save_output, 65 | log_file=output_file_name) 66 | 67 | if self.pages == -1 or (self.pages - 1 * 20) > tweet_count: 68 | logger.info("Switching to search mode. Profile Limit exhausted") 69 | ts = TweetScrapperSearch(search_from_accounts=self.username, 70 | search_since_date=TweetScrapperSearch.twitter_from_date, 71 | search_till_date=last_tweet_time) 72 | append_tweet_count, last_tweet_id, last_tweet_time, dump_path = ts.get_search_tweets(save_output) 73 | tweet_count += append_tweet_count 74 | 75 | return tweet_count, last_tweet_id, last_tweet_time, dump_path 76 | return 0, 0, 0, output_file_name 77 | 78 | 79 | if __name__ == '__main__': 80 | logging.basicConfig(level=logging.DEBUG) 81 | l_ts = TweetScrapperProfile("5hirish", 40, 'twitter.csv', 'csv') 82 | l_tweet_count, l_tweet_id, l_tweet_time, l_dump_path = l_ts.get_profile_tweets(True) 83 | # for l_tweet in l_extracted_tweets: 84 | # print(str(l_tweet)) 85 | print(l_tweet_count) 86 | -------------------------------------------------------------------------------- /tweetscrape/search_tweets.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from datetime import datetime 3 | from math import ceil 4 | 5 | from tweetscrape.tweets_scrape import TweetScrapper 6 | 7 | logger = logging.getLogger(__name__) 8 | 9 | 10 | class TweetScrapperSearch(TweetScrapper): 11 | """ 12 | Search syntax for query, each filter is white space separated 13 | eg: Election India NDA "BJP" 2019 OR 2018 -Asia #India OR #BJP from:narendramodi to:NITIAayog @NDTV since:2017-08-01 until:2019-06-15 14 | 15 | 1) All of these words: each white space separated 16 | 2) This exact phrase: `""` term in quotation marks 17 | 3) Any of these words: `OR` operator separated, each operator separated 18 | 4) None of these words: `-` operator as prefix to the term, each white space separated 19 | 5) These hash-tags: `#` operator as prefix to the term, each `OR` separated 20 | 6) From these accounts: `from:` as prefix to the term, each `OR` separated 21 | 7) To these accounts: `to:` as prefix to the term, each `OR` separated 22 | 8) Mentioning these accounts: `@` as prefix to the term, each `OR` separated 23 | 9) Near this place: `near:` as prefix to the term and `""` term in quotation marks 24 | and `within:` as range with `mi` as suffix miles 25 | 10) From this date: `since:` as prefix to from date and `until:` as prefix to till date. Date format as `YYYY-MM-DD` 26 | 27 | Can specify language. Use language codes. eg. English - `en` 28 | 29 | """ 30 | 31 | search_term = None 32 | search_type = None 33 | pages = None 34 | 35 | twitter_from_date = "2006-03-21" 36 | previous_last_tweet_id = "" 37 | max_retry_count = 6 38 | retry_count = 0 39 | 40 | def __init__(self, 41 | search_all="", search_exact="", search_any="", search_excludes="", search_hashtags="", 42 | search_from_accounts="", search_to_accounts="", search_mentions="", 43 | search_near_place="", search_near_distance="", 44 | search_till_date="", search_since_date="", 45 | num_tweets=40, language='', 46 | tweet_dump_path="", tweet_dump_format="", 47 | request_proxies=None): 48 | 49 | self.search_type = "typd" 50 | 51 | if num_tweets > 0: 52 | self.pages = ceil(num_tweets/20) 53 | else: 54 | self.pages = -1 55 | 56 | self.search_since_date = search_since_date 57 | 58 | self.intermediate_query = self.construct_query(search_all, search_exact, search_any, 59 | search_excludes, search_hashtags, 60 | search_from_accounts, search_to_accounts, search_mentions, 61 | search_near_place, search_near_distance) 62 | 63 | self.time_query = self.update_time_interval(search_since_date, search_till_date) 64 | 65 | # self.search_term = parse.quote(constructed_search_query) 66 | 67 | # if search_all.startswith("#"): 68 | # self.search_type = "hash" 69 | # else: 70 | # self.search_type = "typd" 71 | 72 | self.__twitter_search_init_url__ = 'https://twitter.com/search' 73 | 74 | self.__twitter_search_init_params__ = { 75 | 'vertical': 'default', 76 | 'src': self.search_type, 77 | } 78 | 79 | self.__twitter_search_params_recursive__ = { 80 | 'vertical': 'default', 81 | 'src': self.search_type, 82 | 'l': language, 83 | 'include_available_features': 1, 84 | 'include_entities': 1, 85 | 'include_new_items_bar': 'true' 86 | } 87 | 88 | super().__init__(None, None, None, request_proxies, 89 | self.pages, tweet_dump_path, tweet_dump_format) 90 | 91 | def get_search_tweets(self, latest_tweets=True, save_output=False): 92 | if self.time_query is not None and self.time_query != "": 93 | search_query = self.intermediate_query + " " + self.time_query 94 | else: 95 | search_query = self.intermediate_query 96 | 97 | logger.info("Search:|{0}|".format(search_query)) 98 | 99 | if latest_tweets: 100 | self.__twitter_search_init_params__['f'] = 'tweets' 101 | self.__twitter_search_init_params__['q'] = search_query 102 | 103 | self.update_request_url(self.__twitter_search_init_url__) 104 | self.update_request_params( 105 | twitter_request_url=self.__twitter_search_init_url__, 106 | twitter_request_params=self.__twitter_search_init_params__, 107 | update_refer=True) 108 | 109 | output_file_name = '/' + search_query + '_search' 110 | tweet_count, last_tweet_id, last_tweet_time, dump_path = self.execute_twitter_request(search_term=search_query, 111 | log_output=save_output, 112 | log_file=output_file_name) 113 | # Stop Iteration ? 114 | if last_tweet_time != "" and (self.pages == -1 or (self.pages - 1) * 20 > tweet_count): 115 | logger.info("Recursive search. Profile Limit exhausted: Till:" + last_tweet_time) 116 | 117 | if latest_tweets: 118 | self.__twitter_search_params_recursive__['f'] = 'tweets' 119 | self.__twitter_search_params_recursive__['q'] = search_query 120 | self.__twitter_search_init_params__['q'] = search_query 121 | 122 | # self.update_request_url(self.__twitter_search_url__) 123 | self.update_request_params( 124 | twitter_request_url=self.__twitter_search_init_url__, 125 | twitter_request_params=self.__twitter_search_init_params__, 126 | update_refer=True) 127 | self.clear_old_cursor() 128 | 129 | if self.previous_last_tweet_id != "" and self.previous_last_tweet_id == last_tweet_id: 130 | logger.info("Circular search detected. Taking measures...") 131 | 132 | # Try changing user-agent (Best case) 133 | self.switch_request_user_agent() 134 | # Try changing request proxy 135 | self.switch_request_proxy() 136 | # Try adding a request delay (Works in front-end) 137 | # time.sleep(random.choice(self.__twitter_request_delays__)) 138 | # Try stepping the date (Worst case) 139 | 140 | if self.retry_count > self.max_retry_count: 141 | # Finally give up ... 142 | logger.warning("Tried all measures giving up!") 143 | return tweet_count, last_tweet_id, last_tweet_time, dump_path 144 | 145 | self.retry_count += 1 146 | 147 | else: 148 | self.previous_last_tweet_id = last_tweet_id 149 | 150 | if self.search_since_date is None or self.search_since_date == '': 151 | search_since = self.twitter_from_date 152 | else: 153 | search_since = self.search_since_date 154 | 155 | self.time_query = self.update_time_interval(search_since_date=search_since, 156 | search_till_date=last_tweet_time) 157 | append_tweet_count, last_tweet_id, last_tweet_time, dump_path = self.get_search_tweets(save_output) 158 | tweet_count += append_tweet_count 159 | 160 | return tweet_count, last_tweet_id, last_tweet_time, dump_path 161 | 162 | def update_time_interval(self, search_since_date, search_till_date): 163 | 164 | if search_till_date is not None and search_till_date != "" and valid_date_format(search_till_date, 165 | self.twitter_date_format): 166 | search_till_date = "until:" + search_till_date 167 | 168 | if search_since_date is not None and search_since_date != "" and valid_date_format(search_since_date, 169 | self.twitter_date_format): 170 | if datetime.strptime(search_since_date, self.twitter_date_format) <= \ 171 | datetime.strptime(search_till_date.replace('until:', ''), self.twitter_date_format): 172 | 173 | search_since_date = "since:" + search_since_date 174 | else: 175 | search_since_date = "since:" + self.twitter_from_date 176 | else: 177 | search_since_date = "since:" + self.twitter_from_date 178 | logger.info(search_since_date) 179 | if (search_since_date is not None and search_since_date != "") and \ 180 | (search_till_date is not None and search_till_date != ""): 181 | return search_since_date + " " + search_till_date 182 | return "" 183 | 184 | @staticmethod 185 | def construct_query(search_all, search_exact, search_any, search_excludes, search_hashtags, 186 | search_from_accounts, search_to_accounts, search_mentions, search_near_place, 187 | search_near_distance): 188 | 189 | search_query_filters = [] 190 | 191 | if search_all is not None and search_all != "": 192 | search_query_filters.append(search_all) 193 | 194 | if search_exact is not None and search_exact != "": 195 | search_exact = "\"" + search_exact + "\"" 196 | search_query_filters.append(search_exact) 197 | 198 | if search_any is not None and search_any != "" and " " in search_any: 199 | search_any = " OR ".join(search_any.split()) 200 | search_query_filters.append(search_any) 201 | 202 | if search_excludes is not None and search_excludes != "": 203 | search_excludes = " -".join(search_excludes.split()) 204 | search_excludes = "-" + search_excludes 205 | search_query_filters.append(search_excludes) 206 | 207 | if search_hashtags is not None and search_hashtags != "": 208 | search_hashtags = prefix_operator(search_hashtags, "#") 209 | search_query_filters.append(search_hashtags) 210 | 211 | if search_from_accounts is not None and search_from_accounts != "": 212 | search_from_accounts = prefix_operator(search_from_accounts, "from:") 213 | search_query_filters.append(search_from_accounts) 214 | 215 | if search_to_accounts is not None and search_to_accounts != "": 216 | search_to_accounts = prefix_operator(search_to_accounts, "to:") 217 | search_query_filters.append(search_to_accounts) 218 | 219 | if search_mentions is not None and search_mentions != "": 220 | search_mentions = prefix_operator(search_mentions, "@") 221 | search_query_filters.append(search_mentions) 222 | 223 | if search_near_place is not None and search_near_place != "": 224 | search_near_place = "near:" + search_near_place 225 | 226 | if search_near_distance is not None and search_near_distance != "": 227 | search_near_distance = "within:" + search_near_distance 228 | else: 229 | search_near_distance = "within:15mi" 230 | 231 | search_query_filters.append(search_near_place) 232 | search_query_filters.append(search_near_distance) 233 | 234 | search_query = ' '.join(search_query_filters) 235 | 236 | return search_query 237 | 238 | 239 | def prefix_operator(query_str, prefix_op): 240 | query_list = query_str.split() 241 | for i, tag in enumerate(query_list): 242 | if tag[0] != prefix_op: 243 | query_list[i] = prefix_op + tag 244 | 245 | return " OR ".join(query_list) 246 | 247 | 248 | def valid_date_format(date_str, date_format='%Y-%m-%d'): 249 | try: 250 | datetime.strptime(date_str, date_format) 251 | except ValueError: 252 | logger.warning("Incorrect data format, should be YYYY-MM-DD") 253 | return False 254 | return True 255 | 256 | 257 | if __name__ == '__main__': 258 | # avengers%20infinity%20war%20%22avengers%22%20-asia%20%23avengers%20from%3Amarvel%20since%3A2019-06-01 259 | # avengers infinity war "avengers" -asia #avengers from:marvel since:2019-06-01 260 | 261 | logging.basicConfig(level=logging.DEBUG) 262 | 263 | # ts = TweetScrapperSearch(search_all="avengers infinity war", tweet_dump_path='twitter.json', 264 | # tweet_dump_format='json') 265 | # 266 | # ts = TweetScrapperSearch(search_from_accounts="BarackObama", 267 | # tweet_dump_path='twitter.csv', 268 | # num_tweets=-1, 269 | # tweet_dump_format='csv') 270 | 271 | ts = TweetScrapperSearch(search_all="trump", 272 | tweet_dump_path='twitter.csv', 273 | num_tweets=100, 274 | search_since_date='2019-01-01', 275 | search_till_date='2019-05-01', 276 | tweet_dump_format='csv') 277 | 278 | # ts = TweetScrapperSearch(search_hashtags="FakeNews Trump", pages=1) 279 | # 280 | # # avengers endgame spiderman OR ironman -spoilers 281 | # ts = TweetScrapperSearch(search_all="avengers endgame", 282 | # search_any="spiderman ironman", 283 | # search_excludes="spoilers", num_tweets=2) 284 | # 285 | # ts = TweetScrapperSearch(search_all="avengers marvel", 286 | # search_hashtags="avengers", 287 | # search_from_accounts="marvel ", 288 | # num_tweets=2) 289 | # 290 | # ts = TweetScrapperSearch(search_all="raptors", 291 | # search_since_date="2019-03-01", search_till_date="2019-06-01", 292 | # num_tweets=1) 293 | # 294 | # ts = TweetScrapperSearch(search_hashtags="raptors", search_near_place="toronto", pages=1) 295 | l_tweet_count, l_tweet_id, l_last_time, l_dump_path = ts.get_search_tweets(latest_tweets=True, save_output=True) 296 | # for l_tweet in l_extracted_tweets: 297 | # print(str(l_tweet)) 298 | print(l_tweet_count) 299 | -------------------------------------------------------------------------------- /tweetscrape/tweets_scrape.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import requests 4 | import logging 5 | import csv 6 | import json 7 | import random 8 | import time 9 | from lxml import etree 10 | from urllib import parse 11 | from datetime import datetime 12 | try: 13 | from json.decoder import JSONDecodeError 14 | except ImportError: 15 | JSONDecodeError = ValueError 16 | 17 | from tweetscrape.model.tweet_model import TweetInfo 18 | from tweetscrape.model.user_model import UserInfo 19 | 20 | logger = logging.getLogger(__name__) 21 | 22 | 23 | class TweetScrapper: 24 | __twitter_request_url__ = None 25 | __twitter_request_header__ = None 26 | __twitter_request_params__ = None 27 | 28 | _tweets_pattern_ = '''//li[contains(@class,"stream-item")]''' 29 | _tweet_stream_max_ = '''//*[@id="timeline" or @id="descendants"]/div''' 30 | 31 | _tweet_min_position = '''data-min-position''' 32 | _tweet_content_pattern_ = '''./div[@class="content"]''' 33 | _tweet_time_ms_pattern_ = '''./div[@class="stream-item-header"]/ 34 | small[@class="time"]/a[contains(@class,"tweet-timestamp")]/span''' 35 | _tweet_text_pattern_ = '''./div[@class="js-tweet-text-container"]//text()''' 36 | _tweet_links_list_pattern_ = '''./div[@class="js-tweet-text-container"]//a''' 37 | 38 | _tweet_reply_count_pattern_ = '''./div[@class="stream-item-footer"]/div/ 39 | span[contains(@class, "ProfileTweet-action--reply")]/span''' 40 | _tweet_like_count_pattern_ = '''./div[@class="stream-item-footer"]/div/ 41 | span[contains(@class, "ProfileTweet-action--favorite")]/span''' 42 | _tweet_retweet_count_pattern_ = '''./div[@class="stream-item-footer"]/div/ 43 | span[contains(@class, "ProfileTweet-action--retweet")]/span''' 44 | 45 | _tweet_user_profile_sidebar_ = '''//div[contains(@class, "ProfileSidebar")]''' 46 | _tweet_user_profile_canopy_ = '''//div[contains(@class, "ProfileCanopy-navBar")]''' 47 | _tweet_user_tweets_count_ = '''//li[contains(@class, "ProfileNav-item--tweets")]/a/span[3]''' 48 | _tweet_user_following_count_ = '''//li[contains(@class, "ProfileNav-item--following")]/a/span[3]''' 49 | _tweet_user_followers_count_ = '''//li[contains(@class, "ProfileNav-item--followers")]/a/span[3]''' 50 | _tweet_user_favorites_count_ = '''//li[contains(@class, "ProfileNav-item--favorites")]/a/span[3]''' 51 | _tweet_user_lists_count_ = '''//li[contains(@class, "ProfileNav-item--lists")]/a/span[3]''' 52 | _tweet_user_name_ = '''//h1[contains(@class, "ProfileHeaderCard-name")]/a/text()''' 53 | _tweet_user_bio_ = '''//p[contains(@class, "ProfileHeaderCard-bio")]//text()''' 54 | _tweet_user_location_ = '''//div[contains(@class, "ProfileHeaderCard-location")]/span[2]/a''' 55 | _tweet_user_url_ = '''//div[contains(@class, "ProfileHeaderCard-url")]/span[2]/a''' 56 | 57 | _tweet_hastag_pattern_ = r'''/hashtag/([0-9a-zA-Z_]*)\?src=hash''' 58 | 59 | __twitter_user_agent__ = [ 60 | 'Mozilla/5.0 (Windows; U; Windows NT 6.1; x64; fr; rv:1.9.2.13) Gecko/20101203 Firebird/3.6.13', 61 | 'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko', 62 | 'Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201', 63 | 'Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16', 64 | 'Mozilla/5.0 (Windows NT 5.2; RW; rv:7.0a1) Gecko/20091211 SeaMonkey/9.23a1pre' 65 | ] 66 | 67 | __twitter_request_header__ = { 68 | 'accept': 'application/json, text/javascript, */*; q=0.01', 69 | 'accept-language': 'en-US,en;q=0.8', 70 | 'user-agent': random.choice(__twitter_user_agent__), 71 | 'x-requested-with': 'XMLHttpRequest', 72 | 'x-twitter-active-user': 'yes', 73 | 'x-twitter-polling': 'true', 74 | } 75 | 76 | __twitter_request_delays__ = [2, 3, 4, 5, 6, 7] 77 | 78 | __twitter_search_url__ = 'https://twitter.com/i/search/timeline' 79 | __twitter_conversation_url__ = 'https://twitter.com/i/{username}/conversation/{parent_tweet_id}' 80 | 81 | twitter_date_format = '%Y-%m-%d' 82 | current_cursor = None 83 | scrape_pages = 2 84 | scraped_user_info = None 85 | 86 | def __init__(self, twitter_request_url, twitter_request_header, 87 | twitter_request_params=None, twitter_request_proxies=None, scrape_pages=2, 88 | twitter_file_path=None, twitter_file_format='csv'): 89 | 90 | self.__twitter_request_url__ = twitter_request_url 91 | if twitter_request_header is not None: 92 | self.__twitter_request_header__ = twitter_request_header 93 | self.__twitter_request_params__ = twitter_request_params 94 | self.__twitter_request_proxies__ = twitter_request_proxies 95 | self.scrape_pages = scrape_pages 96 | self.__twitter_tweet_persist_file_path__ = twitter_file_path 97 | self.__twitter_tweet_persist_file_format__ = twitter_file_format 98 | 99 | self.hashtag_capture = re.compile(self._tweet_hastag_pattern_) 100 | 101 | self.html_parser = etree.HTMLParser(remove_blank_text=True, remove_comments=True) 102 | self.proxy_json = None 103 | 104 | def set_proxy_list(self, proxy_json=None): 105 | """ 106 | :param proxy_json: { 107 | "http": ["http://username:password@address:port", ...], 108 | "https: ["https://username:password@address:port", ...] 109 | } 110 | """ 111 | if isinstance(proxy_json.get("http"), (list,)) or isinstance(proxy_json.get("https"), (list,)): 112 | self.proxy_json = proxy_json 113 | 114 | def switch_request_user_agent(self): 115 | """ 116 | User-Agents: https://udger.com/resources/ua-list 117 | """ 118 | logger.info("Switching user-agent") 119 | self.__twitter_request_header__['user-agent'] = random.choice(self.__twitter_user_agent__) 120 | 121 | def switch_request_proxy(self): 122 | logger.info("Switching proxy") 123 | if self.proxy_json is not None: 124 | request_proxy = { 125 | "http": random.choice(self.proxy_json.get("http")), 126 | "https": random.choice(self.proxy_json.get("https")) 127 | } 128 | self.__twitter_request_proxies__ = request_proxy 129 | 130 | def update_request_params(self, twitter_request_url, twitter_request_params, update_refer=False): 131 | if twitter_request_params is not None: 132 | self.__twitter_request_params__ = twitter_request_params 133 | if update_refer and twitter_request_url != "": 134 | self.update_request_refer(twitter_request_url, self.__twitter_request_params__) 135 | 136 | def update_request_url(self, twitter_request_url): 137 | if twitter_request_url is not None: 138 | self.__twitter_request_url__ = twitter_request_url 139 | 140 | def update_request_refer(self, twitter_request_url, twitter_request_params): 141 | twitter_request_refer = twitter_request_url + '?' + parse.urlencode(twitter_request_params, quote_via=parse.quote) 142 | self.__twitter_request_header__['referer'] = twitter_request_refer 143 | 144 | def clear_old_cursor(self): 145 | self.current_cursor = None 146 | 147 | def execute_twitter_request(self, username=None, search_term=None, conversation_id=None, log_output=False, log_file=None, 148 | add_delay=False, delay_tweet_count=100): 149 | tweet_count = 0 150 | last_tweet_id, last_tweet_time = '', '' 151 | 152 | if self.scrape_pages is None or self.scrape_pages < 0: 153 | is_stream = True 154 | self.scrape_pages = -1 155 | else: 156 | is_stream = False 157 | 158 | total_pages = self.scrape_pages 159 | 160 | if self.current_cursor is not None: 161 | self.__twitter_request_params__['reset_error_state'] = 'false' 162 | self.__twitter_request_params__['max_position'] = self.current_cursor 163 | 164 | while is_stream or self.scrape_pages > 0: 165 | current_tweet_count = 0 166 | min_position = None 167 | 168 | twitter_request_params_encoded = parse.urlencode(self.__twitter_request_params__, quote_via=parse.quote) 169 | 170 | response = requests.get(self.__twitter_request_url__, 171 | headers=self.__twitter_request_header__, 172 | params=twitter_request_params_encoded, 173 | proxies=self.__twitter_request_proxies__) 174 | 175 | if response.ok and response.status_code == 200: 176 | if search_term is not None: 177 | self.__twitter_request_url__ = self.__twitter_search_url__ 178 | elif username is not None and conversation_id is not None: 179 | self.__twitter_request_url__ = self.__twitter_conversation_url__\ 180 | .format(username=username, parent_tweet_id=conversation_id) 181 | 182 | logger.debug("Page {0} request: {1}".format(abs(self.scrape_pages), response.status_code)) 183 | 184 | try: 185 | tweet_json = response.json() 186 | 187 | try: 188 | if tweet_json.get('has_more_items'): 189 | num_new_tweets = tweet_json.get('new_latent_count') 190 | min_position = tweet_json.get('min_position') 191 | else: 192 | logger.info("No more items...!!!") 193 | 194 | if 'items_html' in tweet_json: 195 | tweets_html = tweet_json.get('items_html') 196 | else: 197 | tweets_html = tweet_json.get('page') 198 | 199 | except KeyError: 200 | if search_term is not None: 201 | raise ValueError("Oops! Something went wrong while searching {0}.".format(search_term)) 202 | elif username is not None: 203 | raise ValueError("Oops! Either {0} does not exist or is private.".format(username)) 204 | else: 205 | raise ValueError("Received no arguments") 206 | 207 | except JSONDecodeError: 208 | tweets_html = response.text 209 | 210 | if log_output: 211 | save_output_log(log_file + '.html', tweets_html) 212 | 213 | html_tree = etree.fromstring(tweets_html, self.html_parser) 214 | 215 | if html_tree is not None: 216 | if username is not None and conversation_id is None: 217 | profile_sidebar = html_tree.xpath(self._tweet_user_profile_sidebar_) 218 | profile_canopy = html_tree.xpath(self._tweet_user_profile_canopy_) 219 | if profile_sidebar is not None and len(profile_sidebar) > 0 and \ 220 | profile_canopy is not None and len(profile_canopy) > 0: 221 | self.extract_user_data(username, profile_sidebar, profile_canopy) 222 | 223 | tweet_stream = html_tree.xpath(self._tweet_stream_max_) 224 | if tweet_stream is not None and len(tweet_stream) > 0: 225 | min_position = tweet_stream[0].attrib['data-min-position'] 226 | tweet_list = html_tree.xpath(self._tweets_pattern_) 227 | 228 | tweets_generator = self.extract_tweets_data(tweet_list) 229 | tweet_id, tweet_time, current_tweet_count = self.persist_tweets(tweets_generator) 230 | 231 | if tweet_time is not None and tweet_time != "": 232 | last_tweet_time = tweet_time 233 | if tweet_id is not None and tweet_id != "": 234 | last_tweet_id = tweet_id 235 | tweet_count += current_tweet_count 236 | 237 | logger.debug( 238 | "Extracting {0} tweets of {1} page...".format(len(tweet_list), 239 | total_pages - self.scrape_pages + 1)) 240 | 241 | if not is_stream: 242 | self.scrape_pages += -1 243 | 244 | self.current_cursor = min_position 245 | 246 | if current_tweet_count > 0 and min_position is not None: 247 | # composed_count: 0 248 | # interval: 30000 249 | # latent_count: 0 250 | # self.__twitter_request_params__['min_position'] = last_tweet_id 251 | self.__twitter_request_params__['reset_error_state'] = 'false' 252 | self.__twitter_request_params__['max_position'] = self.current_cursor 253 | 254 | if conversation_id is not None: 255 | self.__twitter_request_params__ = { 256 | 'include_available_features': 1, 257 | 'include_entities': 1, 258 | 'max_position': self.current_cursor, 259 | 'reset_error_state': 'false' 260 | } 261 | # self.__twitter_request_params__.pop('conversation_id', None) 262 | 263 | if add_delay and tweet_count % delay_tweet_count == 0: 264 | delay = random.choice(self.__twitter_request_delays__) 265 | time.sleep(delay) 266 | else: 267 | logger.info("End of tweet stream...") 268 | return tweet_count, last_tweet_id, last_tweet_time, self.__twitter_tweet_persist_file_path__ 269 | 270 | logger.info("Total {0} tweets extracted.".format(tweet_count)) 271 | return tweet_count, last_tweet_id, last_tweet_time, self.__twitter_tweet_persist_file_path__ 272 | 273 | def extract_tweets_data(self, tweet_list): 274 | if tweet_list is not None: 275 | for tweet in tweet_list: 276 | if 'data-item-type' in tweet.attrib and tweet.attrib.get('data-item-type') == "tweet": 277 | item_id = tweet.attrib.get('data-item-id') 278 | item_type = tweet.attrib.get('data-item-type') 279 | tweet_data = TweetInfo(item_id, item_type) 280 | 281 | if len(tweet.getchildren()) > 0: 282 | tweet_meta = tweet.getchildren()[0] 283 | tweet_id = tweet_meta.attrib.get('data-tweet-id') 284 | tweet_author = tweet_meta.attrib.get('data-screen-name') 285 | tweet_author_name = tweet_meta.attrib.get('data-name') 286 | tweet_author_id = tweet_meta.attrib.get('data-user-id') 287 | if "data-conversation-id" in tweet_meta.attrib: 288 | tweet_has_parent = tweet_meta.attrib.get('data-has-parent-tweet', False) 289 | tweet_conversation_id = tweet_meta.attrib.get('data-conversation-id', None) 290 | tweet_data.set_tweet_conversation(tweet_conversation_id, tweet_has_parent) 291 | if "data-retweet-id" in tweet_meta.attrib: 292 | tweet_retweeter = tweet_meta.attrib.get('data-retweeter') 293 | tweet_data.set_retweeter(tweet_retweeter) 294 | tweet_data.set_tweet_author(tweet_author, tweet_author_name, tweet_author_id) 295 | 296 | tweet_content = tweet_meta.xpath(self._tweet_content_pattern_) 297 | if len(tweet_content) > 0: 298 | tweet_time_ms = tweet_content[0].xpath(self._tweet_time_ms_pattern_)[0] \ 299 | .attrib.get('data-time-ms') 300 | tweet_data.set_tweet_time_ms(tweet_time_ms) 301 | 302 | tweet_text = tweet_content[0].xpath(self._tweet_text_pattern_) 303 | tweet_text = ''.join(tweet_text).replace('\n', '') 304 | tweet_text = tweet_text.strip() 305 | tweet_data.set_tweet_text(tweet_text) 306 | 307 | tweet_links_raw = tweet_content[0].xpath(self._tweet_links_list_pattern_) 308 | 309 | for raw_link in tweet_links_raw: 310 | raw_url = raw_link.attrib.get('href') 311 | if raw_url.startswith('https://') or raw_url.startswith('http://'): 312 | tweet_data.set_tweet_links(raw_url) 313 | elif raw_url.startswith('/hashtag/'): 314 | hash_tag_group = re.match(self.hashtag_capture, raw_url) 315 | if hash_tag_group is not None and hash_tag_group.group(1) is not None: 316 | hash_tag = "#" + hash_tag_group.group(1) 317 | tweet_data.set_tweet_hashtags(hash_tag) 318 | else: 319 | mention = raw_url.replace('/', '@') 320 | tweet_data.set_tweet_mentions(mention) 321 | 322 | tweet_replies = tweet_content[0].xpath(self._tweet_reply_count_pattern_) 323 | tweet_replies_count = tweet_replies[0].attrib.get('data-tweet-stat-count') 324 | tweet_likes = tweet_content[0].xpath(self._tweet_like_count_pattern_) 325 | tweet_likes_count = tweet_likes[0].attrib.get('data-tweet-stat-count') 326 | tweet_retweets = tweet_content[0].xpath(self._tweet_retweet_count_pattern_) 327 | tweet_retweets_count = tweet_retweets[0].attrib.get('data-tweet-stat-count') 328 | 329 | tweet_data.set_tweet_interactions(tweet_replies_count, tweet_likes_count, 330 | tweet_retweets_count) 331 | 332 | yield tweet_data 333 | 334 | def persist_tweets(self, tweets_generator, dump_mode='a'): 335 | if self.__twitter_tweet_persist_file_path__ is None or self.__twitter_tweet_persist_file_path__ == "": 336 | self.__twitter_tweet_persist_file_format__ = 'csv' 337 | self.__twitter_tweet_persist_file_path__ = os.getcwd() + 'tweets_dump.' + \ 338 | self.__twitter_tweet_persist_file_format__ 339 | 340 | with open(self.__twitter_tweet_persist_file_path__, dump_mode, encoding="utf-8") as tweet_fp: 341 | tweet_count = 0 342 | last_tweet_id = '' 343 | last_tweet_timestamp = '' 344 | 345 | tweet_csv_writer = csv.DictWriter(tweet_fp, fieldnames=TweetInfo.tweet_fields) 346 | 347 | if self.__twitter_tweet_persist_file_format__.lower() != 'csv' and tweet_fp.tell() != 0: 348 | tweet_fp.seek(tweet_fp.tell() - 1, os.SEEK_SET) 349 | tweet_fp.truncate() 350 | tweet_fp.write(",") 351 | 352 | for tweet in tweets_generator: 353 | last_tweet_id = tweet.get_tweet_id() 354 | last_tweet_timestamp = tweet.get_tweet_time_ms() 355 | tweet_count += 1 356 | if self.__twitter_tweet_persist_file_format__.lower() == 'csv': 357 | if tweet_fp.tell() == 0: 358 | tweet_csv_writer.writeheader() 359 | tweet_csv_writer.writerow(tweet.get_json()) 360 | else: 361 | if tweet_fp.tell() == 0: 362 | tweet_fp.write("[") 363 | json.dump(tweet.get_json(), tweet_fp) 364 | tweet_fp.write(",") 365 | if self.__twitter_tweet_persist_file_format__.lower() != 'csv': 366 | tweet_fp.seek(tweet_fp.tell() - 1, os.SEEK_SET) 367 | tweet_fp.truncate() 368 | tweet_fp.write("]") 369 | 370 | try: 371 | last_datetime = datetime.fromtimestamp(int(last_tweet_timestamp) // 1000) 372 | last_tweet_timestamp = datetime.strftime(last_datetime, self.twitter_date_format) 373 | except ValueError: 374 | last_tweet_timestamp = "" 375 | logger.warning("Unable to get last tweet timestamp") 376 | 377 | logger.debug("Batch written to file:{0}".format(self.__twitter_tweet_persist_file_path__)) 378 | return last_tweet_id, last_tweet_timestamp, tweet_count 379 | 380 | def extract_user_data(self, user_handle, profile_sidebar, profile_canopy): 381 | 382 | user_display_name = profile_sidebar[0].xpath(self._tweet_user_name_) 383 | if user_display_name is not None and len(user_display_name) > 0: 384 | user_display_name_val = ''.join(user_display_name) 385 | else: 386 | user_display_name_val = None 387 | user_bio_val = profile_sidebar[0].xpath(self._tweet_user_bio_) 388 | if user_bio_val is not None and len(user_bio_val) > 0: 389 | user_bio_val = ''.join(user_bio_val).replace('\xa0', '') 390 | else: 391 | user_bio_val = None 392 | user_location = profile_sidebar[0].xpath(self._tweet_user_location_) 393 | if user_location is not None and len(user_location) > 0: 394 | user_location_id_val = user_location[0].attrib.get('data-place-id') 395 | user_location_val = user_location[0].text 396 | else: 397 | user_location_id_val, user_location_val = None, None 398 | user_url = profile_sidebar[0].xpath(self._tweet_user_url_) 399 | if user_url is not None and len(user_url) > 0: 400 | user_url_val = user_url[0].attrib.get('title') 401 | else: 402 | user_url_val = None 403 | 404 | user_tweets_count = profile_canopy[0].xpath(self._tweet_user_tweets_count_) 405 | user_count_val = user_tweets_count[0].attrib.get('data-count') 406 | user_following = profile_canopy[0].xpath(self._tweet_user_following_count_) 407 | user_following_val = user_following[0].attrib.get('data-count') 408 | user_follower = profile_canopy[0].xpath(self._tweet_user_followers_count_) 409 | user_follower_val = user_follower[0].attrib.get('data-count') 410 | user_favorites = profile_canopy[0].xpath(self._tweet_user_favorites_count_) 411 | if user_favorites is not None and len(user_favorites) > 0: 412 | user_favorites_val = user_favorites[0].attrib.get('data-count') 413 | else: 414 | user_favorites_val = None 415 | 416 | self.scraped_user_info = UserInfo( 417 | user_handle, 418 | user_display_name_val, 419 | user_bio_val, 420 | user_location_val, 421 | user_location_id_val, 422 | user_url_val, 423 | user_count_val, 424 | user_following_val, 425 | user_follower_val, 426 | user_favorites_val 427 | ) 428 | 429 | def get_user_info(self): 430 | if self.scraped_user_info is not None: 431 | return self.scraped_user_info.get_json() 432 | return None 433 | 434 | 435 | def save_output_log(filename, data): 436 | if filename is not None and data is not None: 437 | file_path = os.path.dirname(os.path.realpath(__file__)) 438 | with open(file_path + filename, 'w') as fp: 439 | fp.write(data) 440 | -------------------------------------------------------------------------------- /tweetscrape/twitter_scrape.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import argparse 5 | import sys 6 | import logging 7 | 8 | from tweetscrape import __version__ 9 | from tweetscrape.profile_tweets import TweetScrapperProfile 10 | from tweetscrape.search_tweets import TweetScrapperSearch 11 | 12 | __author__ = "Shirish Kadam" 13 | __copyright__ = "Copyright (C) 2018 Shirish Kadam" 14 | __license__ = "GNU General Public License v3 (GPLv3)" 15 | 16 | _logger = logging.getLogger(__name__) 17 | 18 | 19 | def parse_args(args): 20 | """Parse command line parameters 21 | 22 | Args: 23 | args ([str]): command line parameters as list of strings 24 | 25 | Returns: 26 | :obj:`argparse.Namespace`: command line parameters namespace 27 | """ 28 | parser = argparse.ArgumentParser( 29 | description="Effortlessly scrape tweets from twitter...") 30 | parser.add_argument( 31 | '--version', 32 | action='version', 33 | version='Tweet Scrapper v{ver}'.format(ver=__version__)) 34 | parser.add_argument( 35 | '-u', 36 | dest="username", 37 | help="Username of the twitter profile eg. @5hirish", 38 | type=str, 39 | metavar="") 40 | parser.add_argument( 41 | '--all', 42 | dest="search_all", 43 | help="Search all of these words", 44 | type=str, 45 | metavar="") 46 | parser.add_argument( 47 | '--exact', 48 | dest="search_exact", 49 | help="Search this exact phrase", 50 | type=str, 51 | metavar="") 52 | parser.add_argument( 53 | '--any', 54 | dest="search_any", 55 | help="Search any of these words", 56 | type=str, 57 | metavar="") 58 | parser.add_argument( 59 | '--exclude', 60 | dest="search_excludes", 61 | help="Search excluding these words", 62 | type=str, 63 | metavar="") 64 | parser.add_argument( 65 | '--hashtag', 66 | dest="search_hashtags", 67 | help="Search these hashtags", 68 | type=str, 69 | metavar="") 70 | parser.add_argument( 71 | '--from', 72 | dest="search_from_accounts", 73 | help="Search tweets from these accounts", 74 | type=str, 75 | metavar="") 76 | parser.add_argument( 77 | '--to', 78 | dest="search_to_accounts", 79 | help="Search tweets to these accounts", 80 | type=str, 81 | metavar="") 82 | parser.add_argument( 83 | '--mention', 84 | dest="search_mentions", 85 | help="Search tweets mentioning these accounts", 86 | type=str, 87 | metavar="") 88 | parser.add_argument( 89 | '--near', 90 | dest="search_near_place", 91 | help="Search tweets near this place", 92 | type=str, 93 | metavar="") 94 | parser.add_argument( 95 | '--until', 96 | dest="search_till_date", 97 | help="Search tweets until this date: YYYY-MM-DD", 98 | type=str, 99 | metavar="") 100 | parser.add_argument( 101 | '--since', 102 | dest="search_since_date", 103 | help="Search tweets since this date: YYYY-MM-DD", 104 | type=str, 105 | metavar="") 106 | parser.add_argument( 107 | '-n', 108 | dest="num_tweets", 109 | help="Number of tweets to fetch", 110 | type=int, 111 | metavar="") 112 | parser.add_argument( 113 | '-l', 114 | dest="language", 115 | help="Search tweets in language from language codes", 116 | type=int, 117 | metavar="") 118 | parser.add_argument( 119 | '-d', 120 | dest="tweet_dump_path", 121 | help="Path of the file to export to", 122 | type=str, 123 | metavar="") 124 | parser.add_argument( 125 | '-f', 126 | dest="tweet_dump_format", 127 | help="File format to export to: json or csv", 128 | type=str, 129 | metavar="") 130 | parser.add_argument( 131 | '--proxy', 132 | dest="request_proxies", 133 | help="The proxies used for scraping. Use serialized dictionary.", 134 | type=str, 135 | metavar="") 136 | parser.add_argument( 137 | '-v', 138 | '--verbose', 139 | dest="loglevel", 140 | help="Sets loglevel to INFO", 141 | action='store_const', 142 | const=logging.INFO) 143 | parser.add_argument( 144 | '-vv', 145 | '--very-verbose', 146 | dest="loglevel", 147 | help="Sets loglevel to DEBUG", 148 | action='store_const', 149 | const=logging.DEBUG) 150 | return parser.parse_args(args) 151 | 152 | 153 | def setup_logging(loglevel): 154 | """Setup basic logging 155 | 156 | Args: 157 | loglevel (int): minimum loglevel for emitting messages 158 | """ 159 | logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s" 160 | logging.basicConfig(level=loglevel, stream=sys.stdout, 161 | format=logformat, datefmt="%Y-%m-%d %H:%M:%S") 162 | 163 | 164 | def main(args): 165 | """Main entry point allowing external calls 166 | 167 | Args: 168 | args ([str]): command line parameter list 169 | """ 170 | args = parse_args(args) 171 | setup_logging(args.loglevel) 172 | _logger.info("Scrapping tweets") 173 | 174 | if args.username is not None: 175 | 176 | ts = TweetScrapperProfile(username=args.username, num_tweets=args.pages, 177 | tweet_dump_path=args.tweet_dump_path, tweet_dump_format=args.tweet_dump_format, 178 | request_proxies=args.request_proxies) 179 | 180 | l_tweet_count, l_tweet_id, l_tweet_time, l_dump_path = ts.get_profile_tweets() 181 | print("Extracted {0} tweets till {1} at {2}".format(l_tweet_count, l_tweet_time, l_dump_path)) 182 | return "Extracted {0} tweets till {1} at {2}".format(l_tweet_count, l_tweet_time, l_dump_path) 183 | 184 | else: 185 | 186 | ts = TweetScrapperSearch(search_all=args.search_all, search_exact=args.search_exact, search_any=args.search_any, 187 | search_excludes=args.search_excludes, search_hashtags=args.search_hashtags, 188 | search_from_accounts=args.search_from_accounts, 189 | search_to_accounts=args.search_to_accounts, search_mentions=args.search_mentions, 190 | search_near_place=args.search_near_place, 191 | search_till_date=args.search_till_date, search_since_date=args.search_since_date, 192 | num_tweets=args.pages, language=args.language, 193 | tweet_dump_path=args.tweet_dump_path, tweet_dump_format=args.tweet_dump_format, 194 | request_proxies=args.request_proxies) 195 | 196 | l_tweet_count, l_tweet_id, l_tweet_time, l_dump_path = ts.get_search_tweets() 197 | print("Extracted {0} tweets till {1} at {2}".format(l_tweet_count, l_tweet_time, l_dump_path)) 198 | return "Extracted {0} tweets till {1} at {2}".format(l_tweet_count, l_tweet_time, l_dump_path) 199 | 200 | 201 | def run(): 202 | """Entry point for console_scripts 203 | """ 204 | main(sys.argv[1:]) 205 | 206 | 207 | if __name__ == "__main__": 208 | run() 209 | -------------------------------------------------------------------------------- /tweetscrape/users_scrape.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from datetime import datetime 3 | 4 | from tweetscrape.tweets_scrape import TweetScrapper 5 | 6 | logger = logging.getLogger(__name__) 7 | 8 | 9 | class TweetScrapperUser(TweetScrapper): 10 | username = "5hirish" 11 | 12 | def __init__(self, username, request_proxies=None): 13 | self.username = username 14 | 15 | self.__twitter_profile_popup_url__ = 'https://twitter.com/i/profiles/popup' 16 | self.__twitter_profile_url__ = 'https://twitter.com/{username}'.format(username=self.username) 17 | 18 | self.__twitter_profile_popup_params__ = { 19 | 'lang': 'en', 20 | 'wants_hovercard': 'true', 21 | } 22 | 23 | self.__twitter_profile_params__ = { 24 | 'include_available_features': 1, 25 | 'include_entities': 1, 26 | 'include_new_items_bar': True 27 | } 28 | 29 | self.__twitter_profile_header__ = { 30 | 'referer': 'https://twitter.com/{username}'.format(username=self.username) 31 | } 32 | 33 | super().__init__(self.__twitter_profile_url__, 34 | self.__twitter_profile_header__, 35 | self.__twitter_profile_params__, 36 | request_proxies, 37 | 1, None, None) 38 | 39 | def get_profile_info(self, save_output=False): 40 | # output_file_name = '/' + self.username + '_profile' 41 | if self.username is not None and self.username != "": 42 | _, _, _, _ = self.execute_twitter_request(username=self.username, 43 | log_output=save_output, 44 | log_file=None) 45 | return self.get_user_info() 46 | return "" 47 | 48 | def get_popup_info(self): 49 | self.__twitter_profile_popup_params__['_'] = int(datetime.now().timestamp()) 50 | self.__twitter_profile_popup_params__['user_id'] = 1 51 | 52 | # XPATH extraction from the popup here 53 | 54 | 55 | if __name__ == '__main__': 56 | logging.basicConfig(level=logging.DEBUG) 57 | 58 | ts = TweetScrapperUser("@5hirish") 59 | l_user = ts.get_profile_info() 60 | print(l_user) 61 | --------------------------------------------------------------------------------