├── .gitignore ├── LICENSE ├── README.md ├── lessons ├── 01_introduction.md └── 02_web_scraping.ipynb ├── requirements.txt └── solutions └── 02_web_scraping_solutions.ipynb /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.toptal.com/developers/gitignore/api/python,jupyternotebooks,visualstudiocode,windows,macos 3 | # Edit at https://www.toptal.com/developers/gitignore?templates=python,jupyternotebooks,visualstudiocode,windows,macos 4 | 5 | ### JupyterNotebooks ### 6 | # gitignore template for Jupyter Notebooks 7 | # website: http://jupyter.org/ 8 | 9 | .ipynb_checkpoints 10 | */.ipynb_checkpoints/* 11 | 12 | # IPython 13 | profile_default/ 14 | ipython_config.py 15 | 16 | # Remove previous ipynb_checkpoints 17 | # git rm -r .ipynb_checkpoints/ 18 | 19 | ### macOS ### 20 | # General 21 | .DS_Store 22 | .AppleDouble 23 | .LSOverride 24 | 25 | # Icon must end with two \r 26 | Icon 27 | 28 | 29 | # Thumbnails 30 | ._* 31 | 32 | # Files that might appear in the root of a volume 33 | .DocumentRevisions-V100 34 | .fseventsd 35 | .Spotlight-V100 36 | .TemporaryItems 37 | .Trashes 38 | .VolumeIcon.icns 39 | .com.apple.timemachine.donotpresent 40 | 41 | # Directories potentially created on remote AFP share 42 | .AppleDB 43 | .AppleDesktop 44 | Network Trash Folder 45 | Temporary Items 46 | .apdisk 47 | 48 | ### Python ### 49 | # Byte-compiled / optimized / DLL files 50 | __pycache__/ 51 | *.py[cod] 52 | *$py.class 53 | 54 | # C extensions 55 | *.so 56 | 57 | # Distribution / packaging 58 | .Python 59 | build/ 60 | develop-eggs/ 61 | dist/ 62 | downloads/ 63 | eggs/ 64 | .eggs/ 65 | lib/ 66 | lib64/ 67 | parts/ 68 | sdist/ 69 | var/ 70 | wheels/ 71 | share/python-wheels/ 72 | *.egg-info/ 73 | .installed.cfg 74 | *.egg 75 | MANIFEST 76 | 77 | # PyInstaller 78 | # Usually these files are written by a python script from a template 79 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 80 | *.manifest 81 | *.spec 82 | 83 | # Installer logs 84 | pip-log.txt 85 | pip-delete-this-directory.txt 86 | 87 | # Unit test / coverage reports 88 | htmlcov/ 89 | .tox/ 90 | .nox/ 91 | .coverage 92 | .coverage.* 93 | .cache 94 | nosetests.xml 95 | coverage.xml 96 | *.cover 97 | *.py,cover 98 | .hypothesis/ 99 | .pytest_cache/ 100 | cover/ 101 | 102 | # Translations 103 | *.mo 104 | *.pot 105 | 106 | # Django stuff: 107 | *.log 108 | local_settings.py 109 | db.sqlite3 110 | db.sqlite3-journal 111 | 112 | # Flask stuff: 113 | instance/ 114 | .webassets-cache 115 | 116 | # Scrapy stuff: 117 | .scrapy 118 | 119 | # Sphinx documentation 120 | docs/_build/ 121 | 122 | # PyBuilder 123 | .pybuilder/ 124 | target/ 125 | 126 | # Jupyter Notebook 127 | 128 | # IPython 129 | 130 | # pyenv 131 | # For a library or package, you might want to ignore these files since the code is 132 | # intended to run in multiple environments; otherwise, check them in: 133 | # .python-version 134 | 135 | # pipenv 136 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 137 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 138 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 139 | # install all needed dependencies. 140 | #Pipfile.lock 141 | 142 | # poetry 143 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 144 | # This is especially recommended for binary packages to ensure reproducibility, and is more 145 | # commonly ignored for libraries. 146 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 147 | #poetry.lock 148 | 149 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 150 | __pypackages__/ 151 | 152 | # Celery stuff 153 | celerybeat-schedule 154 | celerybeat.pid 155 | 156 | # SageMath parsed files 157 | *.sage.py 158 | 159 | # Environments 160 | .env 161 | .venv 162 | env/ 163 | venv/ 164 | ENV/ 165 | env.bak/ 166 | venv.bak/ 167 | 168 | # Spyder project settings 169 | .spyderproject 170 | .spyproject 171 | 172 | # Rope project settings 173 | .ropeproject 174 | 175 | # mkdocs documentation 176 | /site 177 | 178 | # mypy 179 | .mypy_cache/ 180 | .dmypy.json 181 | dmypy.json 182 | 183 | # Pyre type checker 184 | .pyre/ 185 | 186 | # pytype static type analyzer 187 | .pytype/ 188 | 189 | # Cython debug symbols 190 | cython_debug/ 191 | 192 | # PyCharm 193 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can 194 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 195 | # and can be added to the global gitignore or merged into this file. For a more nuclear 196 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 197 | #.idea/ 198 | 199 | ### VisualStudioCode ### 200 | .vscode/* 201 | !.vscode/settings.json 202 | !.vscode/tasks.json 203 | !.vscode/launch.json 204 | !.vscode/extensions.json 205 | !.vscode/*.code-snippets 206 | 207 | # Local History for Visual Studio Code 208 | .history/ 209 | 210 | # Built Visual Studio Code Extensions 211 | *.vsix 212 | 213 | ### VisualStudioCode Patch ### 214 | # Ignore all local history of files 215 | .history 216 | .ionide 217 | 218 | # Support for Project snippet scope 219 | 220 | ### Windows ### 221 | # Windows thumbnail cache files 222 | Thumbs.db 223 | Thumbs.db:encryptable 224 | ehthumbs.db 225 | ehthumbs_vista.db 226 | 227 | # Dump file 228 | *.stackdump 229 | 230 | # Folder config file 231 | [Dd]esktop.ini 232 | 233 | # Recycle Bin used on file shares 234 | $RECYCLE.BIN/ 235 | 236 | # Windows Installer files 237 | *.cab 238 | *.msi 239 | *.msix 240 | *.msm 241 | *.msp 242 | 243 | # Windows shortcuts 244 | *.lnk 245 | 246 | # End of https://www.toptal.com/developers/gitignore/api/python,jupyternotebooks,visualstudiocode,windows,macos 247 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution 4.0 International Public License 58 | 59 | By exercising the Licensed Rights (defined below), You accept and agree 60 | to be bound by the terms and conditions of this Creative Commons 61 | Attribution 4.0 International Public License ("Public License"). To the 62 | extent this Public License may be interpreted as a contract, You are 63 | granted the Licensed Rights in consideration of Your acceptance of 64 | these terms and conditions, and the Licensor grants You such rights in 65 | consideration of benefits the Licensor receives from making the 66 | Licensed Material available under these terms and conditions. 67 | 68 | 69 | Section 1 -- Definitions. 70 | 71 | a. Adapted Material means material subject to Copyright and Similar 72 | Rights that is derived from or based upon the Licensed Material 73 | and in which the Licensed Material is translated, altered, 74 | arranged, transformed, or otherwise modified in a manner requiring 75 | permission under the Copyright and Similar Rights held by the 76 | Licensor. For purposes of this Public License, where the Licensed 77 | Material is a musical work, performance, or sound recording, 78 | Adapted Material is always produced where the Licensed Material is 79 | synched in timed relation with a moving image. 80 | 81 | b. Adapter's License means the license You apply to Your Copyright 82 | and Similar Rights in Your contributions to Adapted Material in 83 | accordance with the terms and conditions of this Public License. 84 | 85 | c. Copyright and Similar Rights means copyright and/or similar rights 86 | closely related to copyright including, without limitation, 87 | performance, broadcast, sound recording, and Sui Generis Database 88 | Rights, without regard to how the rights are labeled or 89 | categorized. For purposes of this Public License, the rights 90 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 91 | Rights. 92 | 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. Share means to provide material to the public by any means or 116 | process that requires permission under the Licensed Rights, such 117 | as reproduction, public display, public performance, distribution, 118 | dissemination, communication, or importation, and to make material 119 | available to the public including in ways that members of the 120 | public may access the material from a place and at a time 121 | individually chosen by them. 122 | 123 | j. Sui Generis Database Rights means rights other than copyright 124 | resulting from Directive 96/9/EC of the European Parliament and of 125 | the Council of 11 March 1996 on the legal protection of databases, 126 | as amended and/or succeeded, as well as other essentially 127 | equivalent rights anywhere in the world. 128 | 129 | k. You means the individual or entity exercising the Licensed Rights 130 | under this Public License. Your has a corresponding meaning. 131 | 132 | 133 | Section 2 -- Scope. 134 | 135 | a. License grant. 136 | 137 | 1. Subject to the terms and conditions of this Public License, 138 | the Licensor hereby grants You a worldwide, royalty-free, 139 | non-sublicensable, non-exclusive, irrevocable license to 140 | exercise the Licensed Rights in the Licensed Material to: 141 | 142 | a. reproduce and Share the Licensed Material, in whole or 143 | in part; and 144 | 145 | b. produce, reproduce, and Share Adapted Material. 146 | 147 | 2. Exceptions and Limitations. For the avoidance of doubt, where 148 | Exceptions and Limitations apply to Your use, this Public 149 | License does not apply, and You do not need to comply with 150 | its terms and conditions. 151 | 152 | 3. Term. The term of this Public License is specified in Section 153 | 6(a). 154 | 155 | 4. Media and formats; technical modifications allowed. The 156 | Licensor authorizes You to exercise the Licensed Rights in 157 | all media and formats whether now known or hereafter created, 158 | and to make technical modifications necessary to do so. The 159 | Licensor waives and/or agrees not to assert any right or 160 | authority to forbid You from making technical modifications 161 | necessary to exercise the Licensed Rights, including 162 | technical modifications necessary to circumvent Effective 163 | Technological Measures. For purposes of this Public License, 164 | simply making modifications authorized by this Section 2(a) 165 | (4) never produces Adapted Material. 166 | 167 | 5. Downstream recipients. 168 | 169 | a. Offer from the Licensor -- Licensed Material. Every 170 | recipient of the Licensed Material automatically 171 | receives an offer from the Licensor to exercise the 172 | Licensed Rights under the terms and conditions of this 173 | Public License. 174 | 175 | b. No downstream restrictions. You may not offer or impose 176 | any additional or different terms or conditions on, or 177 | apply any Effective Technological Measures to, the 178 | Licensed Material if doing so restricts exercise of the 179 | Licensed Rights by any recipient of the Licensed 180 | Material. 181 | 182 | 6. No endorsement. Nothing in this Public License constitutes or 183 | may be construed as permission to assert or imply that You 184 | are, or that Your use of the Licensed Material is, connected 185 | with, or sponsored, endorsed, or granted official status by, 186 | the Licensor or others designated to receive attribution as 187 | provided in Section 3(a)(1)(A)(i). 188 | 189 | b. Other rights. 190 | 191 | 1. Moral rights, such as the right of integrity, are not 192 | licensed under this Public License, nor are publicity, 193 | privacy, and/or other similar personality rights; however, to 194 | the extent possible, the Licensor waives and/or agrees not to 195 | assert any such rights held by the Licensor to the limited 196 | extent necessary to allow You to exercise the Licensed 197 | Rights, but not otherwise. 198 | 199 | 2. Patent and trademark rights are not licensed under this 200 | Public License. 201 | 202 | 3. To the extent possible, the Licensor waives any right to 203 | collect royalties from You for the exercise of the Licensed 204 | Rights, whether directly or through a collecting society 205 | under any voluntary or waivable statutory or compulsory 206 | licensing scheme. In all other cases the Licensor expressly 207 | reserves any right to collect such royalties. 208 | 209 | 210 | Section 3 -- License Conditions. 211 | 212 | Your exercise of the Licensed Rights is expressly made subject to the 213 | following conditions. 214 | 215 | a. Attribution. 216 | 217 | 1. If You Share the Licensed Material (including in modified 218 | form), You must: 219 | 220 | a. retain the following if it is supplied by the Licensor 221 | with the Licensed Material: 222 | 223 | i. identification of the creator(s) of the Licensed 224 | Material and any others designated to receive 225 | attribution, in any reasonable manner requested by 226 | the Licensor (including by pseudonym if 227 | designated); 228 | 229 | ii. a copyright notice; 230 | 231 | iii. a notice that refers to this Public License; 232 | 233 | iv. a notice that refers to the disclaimer of 234 | warranties; 235 | 236 | v. a URI or hyperlink to the Licensed Material to the 237 | extent reasonably practicable; 238 | 239 | b. indicate if You modified the Licensed Material and 240 | retain an indication of any previous modifications; and 241 | 242 | c. indicate the Licensed Material is licensed under this 243 | Public License, and include the text of, or the URI or 244 | hyperlink to, this Public License. 245 | 246 | 2. You may satisfy the conditions in Section 3(a)(1) in any 247 | reasonable manner based on the medium, means, and context in 248 | which You Share the Licensed Material. For example, it may be 249 | reasonable to satisfy the conditions by providing a URI or 250 | hyperlink to a resource that includes the required 251 | information. 252 | 253 | 3. If requested by the Licensor, You must remove any of the 254 | information required by Section 3(a)(1)(A) to the extent 255 | reasonably practicable. 256 | 257 | 4. If You Share Adapted Material You produce, the Adapter's 258 | License You apply must not prevent recipients of the Adapted 259 | Material from complying with this Public License. 260 | 261 | 262 | Section 4 -- Sui Generis Database Rights. 263 | 264 | Where the Licensed Rights include Sui Generis Database Rights that 265 | apply to Your use of the Licensed Material: 266 | 267 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 268 | to extract, reuse, reproduce, and Share all or a substantial 269 | portion of the contents of the database; 270 | 271 | b. if You include all or a substantial portion of the database 272 | contents in a database in which You have Sui Generis Database 273 | Rights, then the database in which You have Sui Generis Database 274 | Rights (but not its individual contents) is Adapted Material; and 275 | 276 | c. You must comply with the conditions in Section 3(a) if You Share 277 | all or a substantial portion of the contents of the database. 278 | 279 | For the avoidance of doubt, this Section 4 supplements and does not 280 | replace Your obligations under this Public License where the Licensed 281 | Rights include other Copyright and Similar Rights. 282 | 283 | 284 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 285 | 286 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 287 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 288 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 289 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 290 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 291 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 292 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 293 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 294 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 295 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 296 | 297 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 298 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 299 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 300 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 301 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 302 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 303 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 304 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 305 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 306 | 307 | c. The disclaimer of warranties and limitation of liability provided 308 | above shall be interpreted in a manner that, to the extent 309 | possible, most closely approximates an absolute disclaimer and 310 | waiver of all liability. 311 | 312 | 313 | Section 6 -- Term and Termination. 314 | 315 | a. This Public License applies for the term of the Copyright and 316 | Similar Rights licensed here. However, if You fail to comply with 317 | this Public License, then Your rights under this Public License 318 | terminate automatically. 319 | 320 | b. Where Your right to use the Licensed Material has terminated under 321 | Section 6(a), it reinstates: 322 | 323 | 1. automatically as of the date the violation is cured, provided 324 | it is cured within 30 days of Your discovery of the 325 | violation; or 326 | 327 | 2. upon express reinstatement by the Licensor. 328 | 329 | For the avoidance of doubt, this Section 6(b) does not affect any 330 | right the Licensor may have to seek remedies for Your violations 331 | of this Public License. 332 | 333 | c. For the avoidance of doubt, the Licensor may also offer the 334 | Licensed Material under separate terms or conditions or stop 335 | distributing the Licensed Material at any time; however, doing so 336 | will not terminate this Public License. 337 | 338 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 339 | License. 340 | 341 | 342 | Section 7 -- Other Terms and Conditions. 343 | 344 | a. The Licensor shall not be bound by any additional or different 345 | terms or conditions communicated by You unless expressly agreed. 346 | 347 | b. Any arrangements, understandings, or agreements regarding the 348 | Licensed Material not stated herein are separate from and 349 | independent of the terms and conditions of this Public License. 350 | 351 | 352 | Section 8 -- Interpretation. 353 | 354 | a. For the avoidance of doubt, this Public License does not, and 355 | shall not be interpreted to, reduce, limit, restrict, or impose 356 | conditions on any use of the Licensed Material that could lawfully 357 | be made without permission under this Public License. 358 | 359 | b. To the extent possible, if any provision of this Public License is 360 | deemed unenforceable, it shall be automatically reformed to the 361 | minimum extent necessary to make it enforceable. If the provision 362 | cannot be reformed, it shall be severed from this Public License 363 | without affecting the enforceability of the remaining terms and 364 | conditions. 365 | 366 | c. No term or condition of this Public License will be waived and no 367 | failure to comply consented to unless expressly agreed to by the 368 | Licensor. 369 | 370 | d. Nothing in this Public License constitutes or may be interpreted 371 | as a limitation upon, or waiver of, any privileges and immunities 372 | that apply to the Licensor or You, including from the legal 373 | processes of any jurisdiction or authority. 374 | 375 | 376 | ======================================================================= 377 | 378 | Creative Commons is not a party to its public 379 | licenses. Notwithstanding, Creative Commons may elect to apply one of 380 | its public licenses to material it publishes and in those instances 381 | will be considered the “Licensor.” The text of the Creative Commons 382 | public licenses is dedicated to the public domain under the CC0 Public 383 | Domain Dedication. Except for the limited purpose of indicating that 384 | material is shared under a Creative Commons public license or as 385 | otherwise permitted by the Creative Commons policies published at 386 | creativecommons.org/policies, Creative Commons does not authorize the 387 | use of the trademark "Creative Commons" or any other trademark or logo 388 | of Creative Commons without its prior written consent including, 389 | without limitation, in connection with any unauthorized modifications 390 | to any of its public licenses or any other arrangements, 391 | understandings, or agreements concerning use of licensed material. For 392 | the avoidance of doubt, this paragraph does not form part of the 393 | public licenses. 394 | 395 | Creative Commons may be contacted at creativecommons.org. 396 | 397 | 398 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # D-Lab Python Web Scraping Workshop 2 | 3 | [![Datahub](https://img.shields.io/badge/launch-datahub-blue)](https://dlab.datahub.berkeley.edu/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fdlab-berkeley%2FPython-Web-Scraping&urlpath=lab%2Ftree%2FPython-Web-Scraping%2F&branch=main) 4 | [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/dlab-berkeley/Python-Web-Scraping/HEAD) 5 | [![License: CC BY 4.0](https://img.shields.io/badge/License-CC_BY_4.0-lightgrey.svg)](https://creativecommons.org/licenses/by/4.0/) 6 | 7 | This repository contains the materials for D-Lab’s Python Web Scraping Workshop. 8 | 9 | ### Prerequisites 10 | 11 | We recommend attending [Python Fundamentals](https://github.com/dlab-berkeley/python-fundamentals) and [Python Data Wrangling](https://github.com/dlab-berkeley/Python-Data-Wrangling/) prior to this workshop. We additionally recommend a basic understanding of HTML and CSS. 12 | 13 | Check D-Lab's [Learning Pathways](https://dlab-berkeley.github.io/dlab-workshops/python_path.html) to figure out which of our workshops to take! 14 | 15 | 16 | ## Workshop Goals 17 | 18 | In this workshop, we cover how to scrape data from the web using Python. Web 19 | scraping involves downloading a webpage's source code and sifting through the 20 | material to extract desired data. 21 | 22 | Web scraping is typically only done when Web APIs are not available. Platforms 23 | like Twitter, Reddit, or The New York Times offer APIs to retrieve data. If you 24 | want to learn how to use web APIs in Python, see D-Lab's [Python Web 25 | APIs](https://github.com/dlab-berkeley/Python-Web-APIs) workshop. 26 | 27 | ## Installation Instructions 28 | 29 | Anaconda is a useful package management software that allows you to run Python 30 | and Jupyter notebooks easily. Installing Anaconda is the easiest way to make 31 | sure you have all the necessary software to run the materials for this workshop. 32 | If you would like to run Python on your own computer, complete the following 33 | steps prior to the workshop: 34 | 35 | 1. [Download and install Anaconda (Python 3.9 36 | distribution)](https://www.anaconda.com/products/individual). Click the 37 | "Download" button. 38 | 39 | 2. Download the Python Web Scraping [workshop 40 | materials](https://github.com/dlab-berkeley/Python-Web-Scraping): 41 | 42 | - Click the green "Code" button in the top right of the repository 43 | information. 44 | - Click "Download Zip". 45 | - Extract this file to a folder on your computer where you can easily 46 | access it (we recommend Desktop). 47 | 48 | 3. Optional: if you're familiar with `git`, you can instead clone this 49 | repository by opening a terminal and entering the command `git clone 50 | git@github.com:dlab-berkeley/Python-Web-Scraping.git`. 51 | 52 | 53 | ## Is Python Not Working on Your Computer? 54 | 55 | If you do not have Anaconda installed and the materials loaded on your workshop 56 | by the time it starts, we *strongly* recommend using the UC Berkeley Datahub to 57 | run the materials for these lessons. You can access the DataHub by clicking this 58 | button: 59 | 60 | [![Datahub](https://img.shields.io/badge/launch-datahub-blue)](https://dlab.datahub.berkeley.edu/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fdlab-berkeley%2FPython-Web-Scraping&urlpath=lab%2Ftree%2FPython-Web-Scraping%2F&branch=main) 61 | 62 | The DataHub downloads this repository, along with any necessary packages, and 63 | allows you to run the materials in a Jupyter notebook that is stored on UC 64 | Berkeley's servers. No installation is necessary from your end - you only need 65 | an internet browser and a CalNet ID to log in. By using the DataHub, you can 66 | save your work and come back to it at any time. When you want to return to your 67 | saved work, just go straight to [DataHub](https://datahub.berkeley.edu), sign 68 | in, and you click on the `Python-Web-Scraping` folder. 69 | 70 | If you don't have a Berkeley CalNet ID, you can still run these lessons in the 71 | cloud, by clicking this button: 72 | 73 | [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/dlab-berkeley/Python-Web-Scraping/HEAD) 74 | 75 | By using this button, however, you cannot save your work. 76 | 77 | ## Run the code 78 | 79 | 1. Open the Anaconda Navigator application. You should see the green snake logo 80 | appear on your screen. Note that this can take a few minutes to load up the 81 | first time. 82 | 83 | 2. Click the "Launch" button under "Jupyter Notebooks" and navigate through your 84 | file system to the `Python-Web-Scraping` folder you downloaded above. Note 85 | that, if you download the materials from GitHub, the folder name may instead 86 | be `Python-Text-Analysis-main`. 87 | 88 | 3. Open the `lessons` folder, and click `01_introduction.md` to begin. 89 | 90 | 4. Press Shift + Enter (or Ctrl + Enter) to run a cell. 91 | 92 | 5. By default, the necessary packages for this workshop should already be 93 | installed. You can install them within the Jupyter notebook by running the 94 | following line in its own cell: 95 | 96 | > ```%pip install -r requirements.txt``` 97 | 98 | Note that all of the above steps can be run from the terminal, if you're 99 | familiar with how to interact with Anaconda in that fashion. However, using 100 | Anaconda Navigator is the easiest way to get started if this is your first time 101 | working with Anaconda. 102 | 103 | # About the UC Berkeley D-Lab 104 | 105 | D-Lab works with Berkeley faculty, research staff, and students to advance 106 | data-intensive social science and humanities research. Our goal at D-Lab is to 107 | provide practical training, staff support, resources, and space to enable you to 108 | use R for your own research applications. Our services cater to all skill levels 109 | and no programming, statistical, or computer science backgrounds are necessary. 110 | We offer these services in the form of workshops, one-to-one consulting, and 111 | working groups that cover a variety of research topics, digital tools, and 112 | programming languages. 113 | 114 | Visit the [D-Lab homepage](https://dlab.berkeley.edu/) to learn more about us. 115 | You can view our [calendar](https://dlab.berkeley.edu/events/calendar) for 116 | upcoming events, learn about how to utilize our 117 | [consulting](https://dlab.berkeley.edu/consulting) and [data 118 | services](https://dlab.berkeley.edu/data), and check out upcoming 119 | [workshops](https://dlab.berkeley.edu/events/workshops). Subscribe to our 120 | [newsletter](https://dlab.berkeley.edu/news/weekly-newsletter) to stay up to 121 | date on D-Lab events, services, and opportunities. 122 | 123 | # Other D-Lab Python Workshops 124 | 125 | D-Lab offers a variety of Python workshops, catered toward different levels of 126 | expertise. 127 | 128 | ## Introductory Workshops 129 | 130 | - [Python Fundamentals](https://github.com/dlab-berkeley/Python-Fundamentals) 131 | - [Python Data Wrangling](https://github.com/dlab-berkeley/Python-Data-Wrangling) 132 | - [Python Data Visualization](https://github.com/dlab-berkeley/Python-Data-Visualization) 133 | 134 | ## Intermediate and Advanced Workshops 135 | 136 | - [Python Geospatial Fundamentals](https://github.com/dlab-berkeley/Geospatial-Data-and-Mapping-in-Python) 137 | - [Python Web Scraping and APIs](https://github.com/dlab-berkeley/Python-Web-Scraping) 138 | - [Python Machine Learning](https://github.com/dlab-berkeley/Python-Machine-Learning) 139 | - [Python Text Analysis](https://github.com/dlab-berkeley/Python-Text-Analysis) 140 | - [Python Deep Learning](https://github.com/dlab-berkeley/Python-Deep-Learning) 141 | 142 | # Contributors 143 | 144 | * [Rochelle Terman](https://github.com/rochelleterman) 145 | * [George McIntire](https://github.com/GeorgeMcIntire) 146 | * [Pratik Sachdeva](https://github.com/pssachdeva) 147 | * [Tom van Nuenen](https://github.com/tomvannuenen) 148 | -------------------------------------------------------------------------------- /lessons/01_introduction.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | The introductory slides for this workshop can be found at this [link](https://docs.google.com/presentation/d/19sE6tSRkGJcIjrStIaYeq_U1KE4Q9lY1r-qbNR7D8ro/edit?usp=sharing). -------------------------------------------------------------------------------- /lessons/02_web_scraping.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Web Scraping with Beautiful Soup\n", 8 | "\n", 9 | "* * * \n", 10 | "\n", 11 | "### Icons used in this notebook\n", 12 | "🔔 **Question**: A quick question to help you understand what's going on.
\n", 13 | "🥊 **Challenge**: Interactive exercise. We'll work through these in the workshop!
\n", 14 | "⚠️ **Warning**: Heads-up about tricky stuff or common mistakes.
\n", 15 | "💡 **Tip**: How to do something a bit more efficiently or effectively.
\n", 16 | "🎬 **Demo**: Showing off something more advanced – so you know what Python can be used for!
\n", 17 | "\n", 18 | "### Learning Objectives\n", 19 | "1. [Reflection: To Scape Or Not To Scrape](#when)\n", 20 | "2. [Extracting and Parsing HTML](#extract)\n", 21 | "3. [Scraping the Illinois General Assembly](#scrape)" 22 | ] 23 | }, 24 | { 25 | "cell_type": "markdown", 26 | "metadata": {}, 27 | "source": [ 28 | "\n", 29 | "\n", 30 | "# To Scrape Or Not To Scrape\n", 31 | "\n", 32 | "When we'd like to access data from the web, we first have to make sure if the website we are interested in offers a Web API. Platforms like Twitter, Reddit, and the New York Times offer APIs. **Check out D-Lab's [Python Web APIs](https://github.com/dlab-berkeley/Python-Web-APIs) workshop if you want to learn how to use APIs.**\n", 33 | "\n", 34 | "However, there are often cases when a Web API does not exist. In these cases, we may have to resort to web scraping, where we extract the underlying HTML from a web page, and directly obtain the information we want. There are several packages in Python we can use to accomplish these tasks. We'll focus two packages: Requests and Beautiful Soup.\n", 35 | "\n", 36 | "Our case study will be scraping information on the [state senators of Illinois](http://www.ilga.gov/senate), as well as the [list of bills](http://www.ilga.gov/senate/SenatorBills.asp?MemberID=1911&GA=98&Primary=True) each senator has sponsored. Before we get started, peruse these websites to take a look at their structure." 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "metadata": {}, 42 | "source": [ 43 | "## Installation\n", 44 | "\n", 45 | "We will use two main packages: [Requests](http://docs.python-requests.org/en/latest/user/quickstart/) and [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/bs4/doc/). Go ahead and install these packages, if you haven't already:" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": null, 51 | "metadata": {}, 52 | "outputs": [], 53 | "source": [ 54 | "%pip install requests" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": null, 60 | "metadata": {}, 61 | "outputs": [], 62 | "source": [ 63 | "%pip install beautifulsoup4" 64 | ] 65 | }, 66 | { 67 | "cell_type": "markdown", 68 | "metadata": {}, 69 | "source": [ 70 | "We'll also install the `lxml` package, which helps support some of the parsing that Beautiful Soup performs:" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": null, 76 | "metadata": {}, 77 | "outputs": [], 78 | "source": [ 79 | "%pip install lxml" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": null, 85 | "metadata": { 86 | "tags": [] 87 | }, 88 | "outputs": [], 89 | "source": [ 90 | "# Import required libraries\n", 91 | "from bs4 import BeautifulSoup\n", 92 | "from datetime import datetime\n", 93 | "import requests\n", 94 | "import time" 95 | ] 96 | }, 97 | { 98 | "cell_type": "markdown", 99 | "metadata": {}, 100 | "source": [ 101 | "\n", 102 | "\n", 103 | "# Extracting and Parsing HTML \n", 104 | "\n", 105 | "In order to succesfully scrape and analyse HTML, we'll be going through the following 4 steps:\n", 106 | "1. Make a GET request\n", 107 | "2. Parse the page with Beautiful Soup\n", 108 | "3. Search for HTML elements\n", 109 | "4. Get attributes and text of these elements" 110 | ] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "metadata": {}, 115 | "source": [ 116 | "## Step 1: Make a GET Request to Obtain a Page's HTML\n", 117 | "\n", 118 | "We can use the Requests library to:\n", 119 | "\n", 120 | "1. Make a GET request to the page, and\n", 121 | "2. Read in the webpage's HTML code.\n", 122 | "\n", 123 | "The process of making a request and obtaining a result resembles that of the Web API workflow. Now, however, we're making a request directly to the website, and we're going to have to parse the HTML ourselves. This is in contrast to being provided data organized into a more straightforward `JSON` or `XML` output." 124 | ] 125 | }, 126 | { 127 | "cell_type": "code", 128 | "execution_count": null, 129 | "metadata": { 130 | "tags": [] 131 | }, 132 | "outputs": [], 133 | "source": [ 134 | "# Make a GET request\n", 135 | "req = requests.get('http://www.ilga.gov/senate/default.asp')\n", 136 | "# Read the content of the server’s response\n", 137 | "src = req.text\n", 138 | "# View some output\n", 139 | "print(src[:1000])" 140 | ] 141 | }, 142 | { 143 | "cell_type": "markdown", 144 | "metadata": {}, 145 | "source": [ 146 | "## Step 2: Parse the Page with Beautiful Soup\n", 147 | "\n", 148 | "Now, we use the `BeautifulSoup` function to parse the reponse into an HTML tree. This returns an object (called a **soup object**) which contains all of the HTML in the original document.\n", 149 | "\n", 150 | "If you run into an error about a parser library, make sure you've installed the `lxml` package to provide Beautiful Soup with the necessary parsing tools." 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "metadata": {}, 157 | "outputs": [], 158 | "source": [ 159 | "# Parse the response into an HTML tree\n", 160 | "soup = BeautifulSoup(src, 'lxml')\n", 161 | "# Take a look\n", 162 | "print(soup.prettify()[:1000])" 163 | ] 164 | }, 165 | { 166 | "cell_type": "markdown", 167 | "metadata": {}, 168 | "source": [ 169 | "The output looks pretty similar to the above, but now it's organized in a `soup` object which allows us to more easily traverse the page." 170 | ] 171 | }, 172 | { 173 | "cell_type": "markdown", 174 | "metadata": {}, 175 | "source": [ 176 | "## Step 3: Search for HTML Elements\n", 177 | "\n", 178 | "Beautiful Soup has a number of functions to find useful components on a page. Beautiful Soup lets you find elements by their:\n", 179 | "\n", 180 | "1. HTML tags\n", 181 | "2. HTML Attributes\n", 182 | "3. CSS Selectors\n", 183 | "\n", 184 | "Let's search first for **HTML tags**. \n", 185 | "\n", 186 | "The function `find_all` searches the `soup` tree to find all the elements with an a particular HTML tag, and returns all of those elements.\n", 187 | "\n", 188 | "What does the example below do?" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": null, 194 | "metadata": {}, 195 | "outputs": [], 196 | "source": [ 197 | "# Find all elements with a certain tag\n", 198 | "a_tags = soup.find_all(\"a\")\n", 199 | "print(a_tags[:10])" 200 | ] 201 | }, 202 | { 203 | "cell_type": "markdown", 204 | "metadata": {}, 205 | "source": [ 206 | "Because `find_all()` is the most popular method in the Beautiful Soup search API, you can use a shortcut for it. If you treat the BeautifulSoup object as though it were a function, then it’s the same as calling `find_all()` on that object. \n", 207 | "\n", 208 | "These two lines of code are equivalent:" 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "execution_count": null, 214 | "metadata": { 215 | "tags": [] 216 | }, 217 | "outputs": [], 218 | "source": [ 219 | "a_tags = soup.find_all(\"a\")\n", 220 | "a_tags_alt = soup(\"a\")\n", 221 | "print(a_tags[0])\n", 222 | "print(a_tags_alt[0])" 223 | ] 224 | }, 225 | { 226 | "cell_type": "markdown", 227 | "metadata": {}, 228 | "source": [ 229 | "How many links did we obtain?" 230 | ] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "execution_count": null, 235 | "metadata": {}, 236 | "outputs": [], 237 | "source": [ 238 | "print(len(a_tags))" 239 | ] 240 | }, 241 | { 242 | "cell_type": "markdown", 243 | "metadata": {}, 244 | "source": [ 245 | "That's a lot! Many elements on a page will have the same HTML tag. For instance, if you search for everything with the `a` tag, you're likely to get more hits, many of which you might not want. Remember, the `a` tag defines a hyperlink, so you'll usually find many on any given page.\n", 246 | "\n", 247 | "What if we wanted to search for HTML tags with certain attributes, such as particular CSS classes? \n", 248 | "\n", 249 | "We can do this by adding an additional argument to the `find_all`. In the example below, we are finding all the `a` tags, and then filtering those with `class_=\"sidemenu\"`." 250 | ] 251 | }, 252 | { 253 | "cell_type": "code", 254 | "execution_count": null, 255 | "metadata": { 256 | "tags": [] 257 | }, 258 | "outputs": [], 259 | "source": [ 260 | "# Get only the 'a' tags in 'sidemenu' class\n", 261 | "side_menus = soup(\"a\", class_=\"sidemenu\")\n", 262 | "side_menus[:5]" 263 | ] 264 | }, 265 | { 266 | "cell_type": "markdown", 267 | "metadata": {}, 268 | "source": [ 269 | "A more efficient way to search for elements on a website is via a **CSS selector**. For this we have to use a different method called `select()`. Just pass a string into the `.select()` to get all elements with that string as a valid CSS selector.\n", 270 | "\n", 271 | "In the example above, we can use `\"a.sidemenu\"` as a CSS selector, which returns all `a` tags with class `sidemenu`." 272 | ] 273 | }, 274 | { 275 | "cell_type": "code", 276 | "execution_count": null, 277 | "metadata": { 278 | "tags": [] 279 | }, 280 | "outputs": [], 281 | "source": [ 282 | "# Get elements with \"a.sidemenu\" CSS Selector.\n", 283 | "selected = soup.select(\"a.sidemenu\")\n", 284 | "selected[:5]" 285 | ] 286 | }, 287 | { 288 | "cell_type": "markdown", 289 | "metadata": {}, 290 | "source": [ 291 | "## 🥊 Challenge: Find All\n", 292 | "\n", 293 | "Use BeautifulSoup to find all the `a` elements with class `mainmenu`." 294 | ] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "execution_count": null, 299 | "metadata": {}, 300 | "outputs": [], 301 | "source": [ 302 | "# YOUR CODE HERE\n" 303 | ] 304 | }, 305 | { 306 | "cell_type": "markdown", 307 | "metadata": {}, 308 | "source": [ 309 | "## Step 4: Get Attributes and Text of Elements\n", 310 | "\n", 311 | "Once we identify elements, we want the access information in that element. Usually, this means two things:\n", 312 | "\n", 313 | "1. Text\n", 314 | "2. Attributes\n", 315 | "\n", 316 | "Getting the text inside an element is easy. All we have to do is use the `text` member of a `tag` object:" 317 | ] 318 | }, 319 | { 320 | "cell_type": "code", 321 | "execution_count": null, 322 | "metadata": { 323 | "tags": [] 324 | }, 325 | "outputs": [], 326 | "source": [ 327 | "# Get all sidemenu links as a list\n", 328 | "side_menu_links = soup.select(\"a.sidemenu\")\n", 329 | "\n", 330 | "# Examine the first link\n", 331 | "first_link = side_menu_links[0]\n", 332 | "print(first_link)\n", 333 | "\n", 334 | "# What class is this variable?\n", 335 | "print('Class: ', type(first_link))" 336 | ] 337 | }, 338 | { 339 | "cell_type": "markdown", 340 | "metadata": {}, 341 | "source": [ 342 | "It's a Beautiful Soup tag! This means it has a `text` member:" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": null, 348 | "metadata": { 349 | "tags": [] 350 | }, 351 | "outputs": [], 352 | "source": [ 353 | "print(first_link.text)" 354 | ] 355 | }, 356 | { 357 | "cell_type": "markdown", 358 | "metadata": {}, 359 | "source": [ 360 | "Sometimes we want the value of certain attributes. This is particularly relevant for `a` tags, or links, where the `href` attribute tells us where the link goes.\n", 361 | "\n", 362 | "💡 **Tip**: You can access a tag’s attributes by treating the tag like a dictionary:" 363 | ] 364 | }, 365 | { 366 | "cell_type": "code", 367 | "execution_count": null, 368 | "metadata": { 369 | "tags": [] 370 | }, 371 | "outputs": [], 372 | "source": [ 373 | "print(first_link['href'])" 374 | ] 375 | }, 376 | { 377 | "cell_type": "markdown", 378 | "metadata": {}, 379 | "source": [ 380 | "## 🥊 Challenge: Extract specific attributes\n", 381 | "\n", 382 | "Extract all `href` attributes for each `mainmenu` URL." 383 | ] 384 | }, 385 | { 386 | "cell_type": "code", 387 | "execution_count": null, 388 | "metadata": {}, 389 | "outputs": [], 390 | "source": [ 391 | "# YOUR CODE HERE\n" 392 | ] 393 | }, 394 | { 395 | "cell_type": "markdown", 396 | "metadata": {}, 397 | "source": [ 398 | "\n", 399 | "\n", 400 | "# Scraping the Illinois General Assembly\n", 401 | "\n", 402 | "Believe it or not, those are really the fundamental tools you need to scrape a website. Once you spend more time familiarizing yourself with HTML and CSS, then it's simply a matter of understanding the structure of a particular website and intelligently applying the tools of Beautiful Soup and Python.\n", 403 | "\n", 404 | "Let's apply these skills to scrape the [Illinois 98th General Assembly](http://www.ilga.gov/senate/default.asp?GA=98).\n", 405 | "\n", 406 | "Specifically, our goal is to scrape information on each senator, including their name, district, and party." 407 | ] 408 | }, 409 | { 410 | "cell_type": "markdown", 411 | "metadata": {}, 412 | "source": [ 413 | "## Scrape and Soup the Webpage\n", 414 | "\n", 415 | "Let's scrape and parse the webpage, using the tools we learned in the previous section." 416 | ] 417 | }, 418 | { 419 | "cell_type": "code", 420 | "execution_count": null, 421 | "metadata": { 422 | "tags": [] 423 | }, 424 | "outputs": [], 425 | "source": [ 426 | "# Make a GET request\n", 427 | "req = requests.get('http://www.ilga.gov/senate/default.asp?GA=98')\n", 428 | "# Read the content of the server’s response\n", 429 | "src = req.text\n", 430 | "# Soup it\n", 431 | "soup = BeautifulSoup(src, \"lxml\")" 432 | ] 433 | }, 434 | { 435 | "cell_type": "markdown", 436 | "metadata": {}, 437 | "source": [ 438 | "## Search for the Table Elements\n", 439 | "\n", 440 | "Our goal is to obtain the elements in the table on the webpage. Remember: rows are identified by the `tr` tag. Let's use `find_all` to obtain these elements." 441 | ] 442 | }, 443 | { 444 | "cell_type": "code", 445 | "execution_count": null, 446 | "metadata": {}, 447 | "outputs": [], 448 | "source": [ 449 | "# Get all table row elements\n", 450 | "rows = soup.find_all(\"tr\")\n", 451 | "len(rows)" 452 | ] 453 | }, 454 | { 455 | "cell_type": "markdown", 456 | "metadata": {}, 457 | "source": [ 458 | "⚠️ **Warning**: Keep in mind: `find_all` gets *all* the elements with the `tr` tag. We only want some of them. If we use the 'Inspect' function in Google Chrome and look carefully, then we can use some CSS selectors to get just the rows we're interested in. Specifically, we want the inner rows of the table:" 459 | ] 460 | }, 461 | { 462 | "cell_type": "code", 463 | "execution_count": null, 464 | "metadata": {}, 465 | "outputs": [], 466 | "source": [ 467 | "# Returns every ‘tr tr tr’ css selector in the page\n", 468 | "rows = soup.select('tr tr tr')\n", 469 | "\n", 470 | "for row in rows[:5]:\n", 471 | " print(row, '\\n')" 472 | ] 473 | }, 474 | { 475 | "cell_type": "markdown", 476 | "metadata": {}, 477 | "source": [ 478 | "It looks like we want everything after the first two rows. Let's work with a single row to start, and build our loop from there." 479 | ] 480 | }, 481 | { 482 | "cell_type": "code", 483 | "execution_count": null, 484 | "metadata": {}, 485 | "outputs": [], 486 | "source": [ 487 | "example_row = rows[2]\n", 488 | "print(example_row.prettify())" 489 | ] 490 | }, 491 | { 492 | "cell_type": "markdown", 493 | "metadata": {}, 494 | "source": [ 495 | "Let's break this row down into its component cells/columns using the `select` method with CSS selectors. Looking closely at the HTML, there are a couple of ways we could do this.\n", 496 | "\n", 497 | "* We could identify the cells by their tag `td`.\n", 498 | "* We could use the the class name `.detail`.\n", 499 | "* We could combine both and use the selector `td.detail`." 500 | ] 501 | }, 502 | { 503 | "cell_type": "code", 504 | "execution_count": null, 505 | "metadata": {}, 506 | "outputs": [], 507 | "source": [ 508 | "for cell in example_row.select('td'):\n", 509 | " print(cell)\n", 510 | "print()\n", 511 | "\n", 512 | "for cell in example_row.select('.detail'):\n", 513 | " print(cell)\n", 514 | "print()\n", 515 | "\n", 516 | "for cell in example_row.select('td.detail'):\n", 517 | " print(cell)\n", 518 | "print()" 519 | ] 520 | }, 521 | { 522 | "cell_type": "markdown", 523 | "metadata": {}, 524 | "source": [ 525 | "We can confirm that these are all the same." 526 | ] 527 | }, 528 | { 529 | "cell_type": "code", 530 | "execution_count": null, 531 | "metadata": { 532 | "tags": [] 533 | }, 534 | "outputs": [], 535 | "source": [ 536 | "assert example_row.select('td') == example_row.select('.detail') == example_row.select('td.detail')" 537 | ] 538 | }, 539 | { 540 | "cell_type": "markdown", 541 | "metadata": {}, 542 | "source": [ 543 | "Let's use the selector `td.detail` to be as specific as possible." 544 | ] 545 | }, 546 | { 547 | "cell_type": "code", 548 | "execution_count": null, 549 | "metadata": {}, 550 | "outputs": [], 551 | "source": [ 552 | "# Select only those 'td' tags with class 'detail' \n", 553 | "detail_cells = example_row.select('td.detail')\n", 554 | "detail_cells" 555 | ] 556 | }, 557 | { 558 | "cell_type": "markdown", 559 | "metadata": {}, 560 | "source": [ 561 | "Most of the time, we're interested in the actual **text** of a website, not its tags. Recall that to get the text of an HTML element, we use the `text` member:" 562 | ] 563 | }, 564 | { 565 | "cell_type": "code", 566 | "execution_count": null, 567 | "metadata": {}, 568 | "outputs": [], 569 | "source": [ 570 | "# Keep only the text in each of those cells\n", 571 | "row_data = [cell.text for cell in detail_cells]\n", 572 | "\n", 573 | "print(row_data)" 574 | ] 575 | }, 576 | { 577 | "cell_type": "markdown", 578 | "metadata": {}, 579 | "source": [ 580 | "Looks good! Now we just use our basic Python knowledge to get the elements of this list that we want. Remember, we want the senator's name, their district, and their party." 581 | ] 582 | }, 583 | { 584 | "cell_type": "code", 585 | "execution_count": null, 586 | "metadata": {}, 587 | "outputs": [], 588 | "source": [ 589 | "print(row_data[0]) # Name\n", 590 | "print(row_data[3]) # District\n", 591 | "print(row_data[4]) # Party" 592 | ] 593 | }, 594 | { 595 | "cell_type": "markdown", 596 | "metadata": {}, 597 | "source": [ 598 | "## Getting Rid of Junk Rows\n", 599 | "\n", 600 | "We saw at the beginning that not all of the rows we got actually correspond to a senator. We'll need to do some cleaning before we can proceed forward. Take a look at some examples:" 601 | ] 602 | }, 603 | { 604 | "cell_type": "code", 605 | "execution_count": null, 606 | "metadata": {}, 607 | "outputs": [], 608 | "source": [ 609 | "print('Row 0:\\n', rows[0], '\\n')\n", 610 | "print('Row 1:\\n', rows[1], '\\n')\n", 611 | "print('Last Row:\\n', rows[-1])" 612 | ] 613 | }, 614 | { 615 | "cell_type": "markdown", 616 | "metadata": {}, 617 | "source": [ 618 | "When we write our for loop, we only want it to apply to the relevant rows. So we'll need to filter out the irrelevant rows. The way to do this is to compare some of these to the rows we do want, see how they differ, and then formulate that in a conditional.\n", 619 | "\n", 620 | "As you can imagine, there a lot of possible ways to do this, and it'll depend on the website. We'll show some here to give you an idea of how to do this." 621 | ] 622 | }, 623 | { 624 | "cell_type": "code", 625 | "execution_count": null, 626 | "metadata": {}, 627 | "outputs": [], 628 | "source": [ 629 | "# Bad rows\n", 630 | "print(len(rows[0]))\n", 631 | "print(len(rows[1]))\n", 632 | "\n", 633 | "# Good rows\n", 634 | "print(len(rows[2]))\n", 635 | "print(len(rows[3]))" 636 | ] 637 | }, 638 | { 639 | "cell_type": "markdown", 640 | "metadata": {}, 641 | "source": [ 642 | "Perhaps good rows have a length of 5. Let's check:" 643 | ] 644 | }, 645 | { 646 | "cell_type": "code", 647 | "execution_count": null, 648 | "metadata": {}, 649 | "outputs": [], 650 | "source": [ 651 | "good_rows = [row for row in rows if len(row) == 5]\n", 652 | "\n", 653 | "# Let's check some rows\n", 654 | "print(good_rows[0], '\\n')\n", 655 | "print(good_rows[-2], '\\n')\n", 656 | "print(good_rows[-1])" 657 | ] 658 | }, 659 | { 660 | "cell_type": "markdown", 661 | "metadata": {}, 662 | "source": [ 663 | "We found a footer row in our list that we'd like to avoid. Let's try something else:" 664 | ] 665 | }, 666 | { 667 | "cell_type": "code", 668 | "execution_count": null, 669 | "metadata": {}, 670 | "outputs": [], 671 | "source": [ 672 | "rows[2].select('td.detail') " 673 | ] 674 | }, 675 | { 676 | "cell_type": "code", 677 | "execution_count": null, 678 | "metadata": {}, 679 | "outputs": [], 680 | "source": [ 681 | "# Bad row\n", 682 | "print(rows[-1].select('td.detail'), '\\n')\n", 683 | "\n", 684 | "# Good row\n", 685 | "print(rows[5].select('td.detail'), '\\n')\n", 686 | "\n", 687 | "# How about this?\n", 688 | "good_rows = [row for row in rows if row.select('td.detail')]\n", 689 | "\n", 690 | "print(\"Checking rows...\\n\")\n", 691 | "print(good_rows[0], '\\n')\n", 692 | "print(good_rows[-1])" 693 | ] 694 | }, 695 | { 696 | "cell_type": "markdown", 697 | "metadata": {}, 698 | "source": [ 699 | "Looks like we found something that worked!" 700 | ] 701 | }, 702 | { 703 | "cell_type": "markdown", 704 | "metadata": {}, 705 | "source": [ 706 | "## Loop it All Together\n", 707 | "\n", 708 | "Now that we've seen how to get the data we want from one row, as well as filter out the rows we don't want, let's put it all together into a loop." 709 | ] 710 | }, 711 | { 712 | "cell_type": "code", 713 | "execution_count": null, 714 | "metadata": { 715 | "tags": [] 716 | }, 717 | "outputs": [], 718 | "source": [ 719 | "# Define storage list\n", 720 | "members = []\n", 721 | "\n", 722 | "# Get rid of junk rows\n", 723 | "valid_rows = [row for row in rows if row.select('td.detail')]\n", 724 | "\n", 725 | "# Loop through all rows\n", 726 | "for row in valid_rows:\n", 727 | " # Select only those 'td' tags with class 'detail'\n", 728 | " detail_cells = row.select('td.detail')\n", 729 | " # Keep only the text in each of those cells\n", 730 | " row_data = [cell.text for cell in detail_cells]\n", 731 | " # Collect information\n", 732 | " name = row_data[0]\n", 733 | " district = int(row_data[3])\n", 734 | " party = row_data[4]\n", 735 | " # Store in a tuple\n", 736 | " senator = (name, district, party)\n", 737 | " # Append to list\n", 738 | " members.append(senator)" 739 | ] 740 | }, 741 | { 742 | "cell_type": "code", 743 | "execution_count": null, 744 | "metadata": {}, 745 | "outputs": [], 746 | "source": [ 747 | "# Should be 61\n", 748 | "len(members)" 749 | ] 750 | }, 751 | { 752 | "cell_type": "markdown", 753 | "metadata": {}, 754 | "source": [ 755 | "Let's take a look at what we have in `members`." 756 | ] 757 | }, 758 | { 759 | "cell_type": "code", 760 | "execution_count": null, 761 | "metadata": {}, 762 | "outputs": [], 763 | "source": [ 764 | "print(members[:5])" 765 | ] 766 | }, 767 | { 768 | "cell_type": "markdown", 769 | "metadata": {}, 770 | "source": [ 771 | "## 🥊 Challenge: Get `href` elements pointing to members' bills \n", 772 | "\n", 773 | "The code above retrieves information on: \n", 774 | "\n", 775 | "- the senator's name,\n", 776 | "- their district number,\n", 777 | "- and their party.\n", 778 | "\n", 779 | "We now want to retrieve the URL for each senator's list of bills. Each URL will follow a specific format. \n", 780 | "\n", 781 | "The format for the list of bills for a given senator is:\n", 782 | "\n", 783 | "`http://www.ilga.gov/senate/SenatorBills.asp?GA=98&MemberID=[MEMBER_ID]&Primary=True`\n", 784 | "\n", 785 | "to get something like:\n", 786 | "\n", 787 | "`http://www.ilga.gov/senate/SenatorBills.asp?MemberID=1911&GA=98&Primary=True`\n", 788 | "\n", 789 | "in which `MEMBER_ID=1911`. \n", 790 | "\n", 791 | "You should be able to see that, unfortunately, `MEMBER_ID` is not currently something pulled out in our scraping code.\n", 792 | "\n", 793 | "Your initial task is to modify the code above so that we also **retrieve the full URL which points to the corresponding page of primary-sponsored bills**, for each member, and return it along with their name, district, and party.\n", 794 | "\n", 795 | "Tips: \n", 796 | "\n", 797 | "* To do this, you will want to get the appropriate anchor element (``) in each legislator's row of the table. You can again use the `.select()` method on the `row` object in the loop to do this — similar to the command that finds all of the `td.detail` cells in the row. Remember that we only want the link to the legislator's bills, not the committees or the legislator's profile page.\n", 798 | "* The anchor elements' HTML will look like `Bills`. The string in the `href` attribute contains the **relative** link we are after. You can access an attribute of a BeatifulSoup `Tag` object the same way you access a Python dictionary: `anchor['attributeName']`. See the documentation for more details.\n", 799 | "* There are a _lot_ of different ways to use BeautifulSoup to get things done. whatever you need to do to pull the `href` out is fine.\n", 800 | "\n", 801 | "The code has been partially filled out for you. Fill it in where it says `#YOUR CODE HERE`. Save the path into an object called `full_path`." 802 | ] 803 | }, 804 | { 805 | "cell_type": "code", 806 | "execution_count": null, 807 | "metadata": { 808 | "tags": [] 809 | }, 810 | "outputs": [], 811 | "source": [ 812 | "# Make a GET request\n", 813 | "req = requests.get('http://www.ilga.gov/senate/default.asp?GA=98')\n", 814 | "# Read the content of the server’s response\n", 815 | "src = req.text\n", 816 | "# Soup it\n", 817 | "soup = BeautifulSoup(src, \"lxml\")\n", 818 | "# Create empty list to store our data\n", 819 | "members = []\n", 820 | "\n", 821 | "# Returns every ‘tr tr tr’ css selector in the page\n", 822 | "rows = soup.select('tr tr tr')\n", 823 | "# Get rid of junk rows\n", 824 | "rows = [row for row in rows if row.select('td.detail')]\n", 825 | "\n", 826 | "# Loop through all rows\n", 827 | "for row in rows:\n", 828 | " # Select only those 'td' tags with class 'detail'\n", 829 | " detail_cells = row.select('td.detail') \n", 830 | " # Keep only the text in each of those cells\n", 831 | " row_data = [cell.text for cell in detail_cells]\n", 832 | " # Collect information\n", 833 | " name = row_data[0]\n", 834 | " district = int(row_data[3])\n", 835 | " party = row_data[4]\n", 836 | "\n", 837 | " # YOUR CODE HERE\n", 838 | " full_path = ''\n", 839 | "\n", 840 | " # Store in a tuple\n", 841 | " senator = (name, district, party, full_path)\n", 842 | " # Append to list\n", 843 | " members.append(senator)" 844 | ] 845 | }, 846 | { 847 | "cell_type": "code", 848 | "execution_count": null, 849 | "metadata": { 850 | "tags": [] 851 | }, 852 | "outputs": [], 853 | "source": [ 854 | "# Uncomment to test \n", 855 | "# members[:5]" 856 | ] 857 | }, 858 | { 859 | "cell_type": "markdown", 860 | "metadata": {}, 861 | "source": [ 862 | "## 🥊 Challenge: Modularize Your Code\n", 863 | "\n", 864 | "Turn the code above into a function that accepts a URL, scrapes the URL for its senators, and returns a list of tuples containing information about each senator. " 865 | ] 866 | }, 867 | { 868 | "cell_type": "code", 869 | "execution_count": null, 870 | "metadata": { 871 | "tags": [] 872 | }, 873 | "outputs": [], 874 | "source": [ 875 | "# YOUR CODE HERE\n", 876 | "def get_members(url):\n", 877 | " return [___]\n" 878 | ] 879 | }, 880 | { 881 | "cell_type": "code", 882 | "execution_count": null, 883 | "metadata": { 884 | "tags": [] 885 | }, 886 | "outputs": [], 887 | "source": [ 888 | "# Test your code\n", 889 | "url = 'http://www.ilga.gov/senate/default.asp?GA=98'\n", 890 | "senate_members = get_members(url)\n", 891 | "len(senate_members)" 892 | ] 893 | }, 894 | { 895 | "cell_type": "markdown", 896 | "metadata": {}, 897 | "source": [ 898 | "## 🥊 Take-home Challenge: Writing a Scraper Function\n", 899 | "\n", 900 | "We want to scrape the webpages corresponding to bills sponsored by each bills.\n", 901 | "\n", 902 | "Write a function called `get_bills(url)` to parse a given bills URL. This will involve:\n", 903 | "\n", 904 | " - requesting the URL using the `requests` library\n", 905 | " - using the features of the `BeautifulSoup` library to find all of the `` elements with the class `billlist`\n", 906 | " - return a _list_ of tuples, each with:\n", 907 | " - description (2nd column)\n", 908 | " - chamber (S or H) (3rd column)\n", 909 | " - the last action (4th column)\n", 910 | " - the last action date (5th column)\n", 911 | " \n", 912 | "This function has been partially completed. Fill in the rest." 913 | ] 914 | }, 915 | { 916 | "cell_type": "code", 917 | "execution_count": null, 918 | "metadata": { 919 | "tags": [] 920 | }, 921 | "outputs": [], 922 | "source": [ 923 | "def get_bills(url):\n", 924 | " src = requests.get(url).text\n", 925 | " soup = BeautifulSoup(src)\n", 926 | " rows = soup.select('tr')\n", 927 | " bills = []\n", 928 | " for row in rows:\n", 929 | " # YOUR CODE HERE\n", 930 | " bill_id =\n", 931 | " description =\n", 932 | " chamber =\n", 933 | " last_action =\n", 934 | " last_action_date =\n", 935 | " bill = (bill_id, description, chamber, last_action, last_action_date)\n", 936 | " bills.append(bill)\n", 937 | " return bills" 938 | ] 939 | }, 940 | { 941 | "cell_type": "code", 942 | "execution_count": null, 943 | "metadata": { 944 | "tags": [] 945 | }, 946 | "outputs": [], 947 | "source": [ 948 | "# Uncomment to test your code\n", 949 | "# test_url = senate_members[0][3]\n", 950 | "# get_bills(test_url)[0:5]" 951 | ] 952 | }, 953 | { 954 | "cell_type": "markdown", 955 | "metadata": {}, 956 | "source": [ 957 | "### Scrape All Bills\n", 958 | "\n", 959 | "Finally, create a dictionary `bills_dict` which maps a district number (the key) onto a list of bills (the value) coming from that district. You can do this by looping over all of the senate members in `members_dict` and calling `get_bills()` for each of their associated bill URLs.\n", 960 | "\n", 961 | "**NOTE:** please call the function `time.sleep(1)` for each iteration of the loop, so that we don't destroy the state's web site." 962 | ] 963 | }, 964 | { 965 | "cell_type": "code", 966 | "execution_count": null, 967 | "metadata": { 968 | "tags": [] 969 | }, 970 | "outputs": [], 971 | "source": [ 972 | "# YOUR CODE HERE\n" 973 | ] 974 | }, 975 | { 976 | "cell_type": "code", 977 | "execution_count": null, 978 | "metadata": { 979 | "tags": [] 980 | }, 981 | "outputs": [], 982 | "source": [ 983 | "# Uncomment to test your code\n", 984 | "# bills_dict[52]" 985 | ] 986 | } 987 | ], 988 | "metadata": { 989 | "anaconda-cloud": {}, 990 | "kernelspec": { 991 | "display_name": "Python 3 (ipykernel)", 992 | "language": "python", 993 | "name": "python3" 994 | }, 995 | "language_info": { 996 | "codemirror_mode": { 997 | "name": "ipython", 998 | "version": 3 999 | }, 1000 | "file_extension": ".py", 1001 | "mimetype": "text/x-python", 1002 | "name": "python", 1003 | "nbconvert_exporter": "python", 1004 | "pygments_lexer": "ipython3", 1005 | "version": "3.8.13" 1006 | }, 1007 | "vscode": { 1008 | "interpreter": { 1009 | "hash": "b6f9fe9f4b7182690503d8ecc2bae97b0ee3ebf54e877167ae4d28c119a56988" 1010 | } 1011 | } 1012 | }, 1013 | "nbformat": 4, 1014 | "nbformat_minor": 4 1015 | } 1016 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests >= 2.26 2 | beautifulsoup4 >= 4.11 3 | lxml >= 4.9 4 | -------------------------------------------------------------------------------- /solutions/02_web_scraping_solutions.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Web Scraping with Beautiful Soup: Solutions" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": null, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "# Import required libraries\n", 17 | "from bs4 import BeautifulSoup\n", 18 | "from datetime import datetime\n", 19 | "import requests\n", 20 | "import time" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "# Make a GET request\n", 30 | "req = requests.get('http://www.ilga.gov/senate/default.asp')\n", 31 | "# Read the content of the server’s response\n", 32 | "src = req.text\n", 33 | "# Parse the response into an HTML tree\n", 34 | "soup = BeautifulSoup(src, 'lxml')" 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "metadata": {}, 40 | "source": [ 41 | "## Challenge: Find All\n", 42 | "\n", 43 | "Use Beautiful Soup to find all the `a` elements with class `mainmenu`." 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "soup.select(\"a.mainmenu\")" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "## Challenge: Extract Specific Attributes\n", 60 | "\n", 61 | "Extract all `href` attributes for each `mainmenu` URL." 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "[link['href'] for link in soup.select(\"a.mainmenu\")]" 71 | ] 72 | }, 73 | { 74 | "cell_type": "markdown", 75 | "metadata": {}, 76 | "source": [ 77 | "## Challenge: Get `href` elements pointing to members' bills\n", 78 | "\n", 79 | "The code above retrieves information on: \n", 80 | "\n", 81 | "- the senator's name,\n", 82 | "- their district number,\n", 83 | "- and their party.\n", 84 | "\n", 85 | "We now want to retrieve the URL for each senator's list of bills. Each URL will follow a specific format. \n", 86 | "\n", 87 | "The format for the list of bills for a given senator is:\n", 88 | "\n", 89 | "`http://www.ilga.gov/senate/SenatorBills.asp?GA=98&MemberID=[MEMBER_ID]&Primary=True`\n", 90 | "\n", 91 | "to get something like:\n", 92 | "\n", 93 | "`http://www.ilga.gov/senate/SenatorBills.asp?MemberID=1911&GA=98&Primary=True`\n", 94 | "\n", 95 | "in which `MEMBER_ID=1911`. \n", 96 | "\n", 97 | "You should be able to see that, unfortunately, `MEMBER_ID` is not currently something pulled out in our scraping code.\n", 98 | "\n", 99 | "Your initial task is to modify the code above so that we also **retrieve the full URL which points to the corresponding page of primary-sponsored bills**, for each member, and return it along with their name, district, and party.\n", 100 | "\n", 101 | "Tips: \n", 102 | "\n", 103 | "* To do this, you will want to get the appropriate anchor element (``) in each legislator's row of the table. You can again use the `.select()` method on the `row` object in the loop to do this — similar to the command that finds all of the `td.detail` cells in the row. Remember that we only want the link to the legislator's bills, not the committees or the legislator's profile page.\n", 104 | "* The anchor elements' HTML will look like `Bills`. The string in the `href` attribute contains the **relative** link we are after. You can access an attribute of a BeatifulSoup `Tag` object the same way you access a Python dictionary: `anchor['attributeName']`. See the documentation for more details.\n", 105 | "* There are a _lot_ of different ways to use BeautifulSoup to get things done. whatever you need to do to pull the `href` out is fine.\n", 106 | "\n", 107 | "The code has been partially filled out for you. Fill it in where it says `#YOUR CODE HERE`. Save the path into an object called `full_path`." 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "# Make a GET request\n", 117 | "req = requests.get('http://www.ilga.gov/senate/default.asp?GA=98')\n", 118 | "# Read the content of the server’s response\n", 119 | "src = req.text\n", 120 | "# Soup it\n", 121 | "soup = BeautifulSoup(src, \"lxml\")\n", 122 | "# Create empty list to store our data\n", 123 | "members = []\n", 124 | "\n", 125 | "# Returns every ‘tr tr tr’ css selector in the page\n", 126 | "rows = soup.select('tr tr tr')\n", 127 | "# Get rid of junk rows\n", 128 | "rows = [row for row in rows if row.select('td.detail')]\n", 129 | "\n", 130 | "# Loop through all rows\n", 131 | "for row in rows:\n", 132 | " # Select only those 'td' tags with class 'detail'\n", 133 | " detail_cells = row.select('td.detail') \n", 134 | " # Keep only the text in each of those cells\n", 135 | " row_data = [cell.text for cell in detail_cells]\n", 136 | " # Collect information\n", 137 | " name = row_data[0]\n", 138 | " district = int(row_data[3])\n", 139 | " party = row_data[4]\n", 140 | " \n", 141 | " # YOUR CODE HERE\n", 142 | " # Extract href\n", 143 | " href = row.select('a')[1]['href']\n", 144 | " # Create full path\n", 145 | " full_path = \"http://www.ilga.gov/senate/\" + href + \"&Primary=True\"\n", 146 | " \n", 147 | " # Store in a tuple\n", 148 | " senator = (name, district, party, full_path)\n", 149 | " # Append to list\n", 150 | " members.append(senator)" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "metadata": {}, 157 | "outputs": [], 158 | "source": [ 159 | "members[:5]" 160 | ] 161 | }, 162 | { 163 | "cell_type": "markdown", 164 | "metadata": {}, 165 | "source": [ 166 | "## Challenge: Modularize Your Code\n", 167 | "\n", 168 | "Turn the code above into a function that accepts a URL, scrapes the URL for its senators, and returns a list of tuples containing information about each senator. " 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": null, 174 | "metadata": {}, 175 | "outputs": [], 176 | "source": [ 177 | "def get_members(url):\n", 178 | " # Make a GET request\n", 179 | " req = requests.get(url)\n", 180 | " # Read the content of the server’s response\n", 181 | " src = req.text\n", 182 | " # Soup it\n", 183 | " soup = BeautifulSoup(src, \"lxml\")\n", 184 | " # Create empty list to store our data\n", 185 | " members = []\n", 186 | "\n", 187 | " # Returns every ‘tr tr tr’ css selector in the page\n", 188 | " rows = soup.select('tr tr tr')\n", 189 | " # Get rid of junk rows\n", 190 | " rows = [row for row in rows if row.select('td.detail')]\n", 191 | "\n", 192 | " # Loop through all rows\n", 193 | " for row in rows:\n", 194 | " # Select only those 'td' tags with class 'detail'\n", 195 | " detail_cells = row.select('td.detail') \n", 196 | " # Keep only the text in each of those cells\n", 197 | " row_data = [cell.text for cell in detail_cells]\n", 198 | " # Collect information\n", 199 | " name = row_data[0]\n", 200 | " district = int(row_data[3])\n", 201 | " party = row_data[4]\n", 202 | "\n", 203 | " # YOUR CODE HERE\n", 204 | " # Extract href\n", 205 | " href = row.select('a')[1]['href']\n", 206 | " # Create full path\n", 207 | " full_path = \"http://www.ilga.gov/senate/\" + href + \"&Primary=True\"\n", 208 | "\n", 209 | " # Store in a tuple\n", 210 | " senator = (name, district, party, full_path)\n", 211 | " # Append to list\n", 212 | " members.append(senator)\n", 213 | " return(members)" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": null, 219 | "metadata": {}, 220 | "outputs": [], 221 | "source": [ 222 | "# Test your code!\n", 223 | "url = 'http://www.ilga.gov/senate/default.asp?GA=98'\n", 224 | "senate_members = get_members(url)\n", 225 | "len(senate_members)" 226 | ] 227 | }, 228 | { 229 | "cell_type": "markdown", 230 | "metadata": {}, 231 | "source": [ 232 | "## Take-home Challenge: Writing a Scraper Function\n", 233 | "\n", 234 | "We want to scrape the webpages corresponding to bills sponsored by each bills.\n", 235 | "\n", 236 | "Write a function called `get_bills(url)` to parse a given bills URL. This will involve:\n", 237 | "\n", 238 | " - requesting the URL using the `requests` library\n", 239 | " - using the features of the `BeautifulSoup` library to find all of the `` elements with the class `billlist`\n", 240 | " - return a _list_ of tuples, each with:\n", 241 | " - description (2nd column)\n", 242 | " - chamber (S or H) (3rd column)\n", 243 | " - the last action (4th column)\n", 244 | " - the last action date (5th column)\n", 245 | " \n", 246 | "This function has been partially completed. Fill in the rest." 247 | ] 248 | }, 249 | { 250 | "cell_type": "code", 251 | "execution_count": null, 252 | "metadata": {}, 253 | "outputs": [], 254 | "source": [ 255 | "def get_bills(url):\n", 256 | " src = requests.get(url).text\n", 257 | " soup = BeautifulSoup(src)\n", 258 | " rows = soup.select('tr tr tr')\n", 259 | " bills = []\n", 260 | " # Iterate over rows\n", 261 | " for row in rows:\n", 262 | " # Grab all bill list cells\n", 263 | " cells = row.select('td.billlist')\n", 264 | " # Keep in mind the name of the senator is not a billlist class!\n", 265 | " if len(cells) == 5:\n", 266 | " row_text = [cell.text for cell in cells]\n", 267 | " # Extract info from row text\n", 268 | " bill_id = row_text[0]\n", 269 | " description = row_text[1]\n", 270 | " chamber = row_text[2]\n", 271 | " last_action = row_text[3]\n", 272 | " last_action_date = row_text[4]\n", 273 | " # Consolidate bill info\n", 274 | " bill = (bill_id, description, chamber, last_action, last_action_date)\n", 275 | " bills.append(bill)\n", 276 | " return bills" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": null, 282 | "metadata": {}, 283 | "outputs": [], 284 | "source": [ 285 | "test_url = senate_members[0][3]\n", 286 | "get_bills(test_url)[0:5]" 287 | ] 288 | }, 289 | { 290 | "cell_type": "markdown", 291 | "metadata": {}, 292 | "source": [ 293 | "### Scrape All Bills\n", 294 | "\n", 295 | "Finally, create a dictionary `bills_dict` which maps a district number (the key) onto a list of bills (the value) coming from that district. You can do this by looping over all of the senate members in `members_dict` and calling `get_bills()` for each of their associated bill URLs.\n", 296 | "\n", 297 | "**NOTE:** please call the function `time.sleep(1)` for each iteration of the loop, so that we don't destroy the state's web site." 298 | ] 299 | }, 300 | { 301 | "cell_type": "code", 302 | "execution_count": 134, 303 | "metadata": {}, 304 | "outputs": [], 305 | "source": [ 306 | "bills_dict = {}\n", 307 | "for member in senate_members[:5]:\n", 308 | " bills_dict[member[1]] = get_bills(member[3])\n", 309 | " time.sleep(1)" 310 | ] 311 | }, 312 | { 313 | "cell_type": "code", 314 | "execution_count": null, 315 | "metadata": {}, 316 | "outputs": [], 317 | "source": [ 318 | "len(bills_dict[52])" 319 | ] 320 | } 321 | ], 322 | "metadata": { 323 | "anaconda-cloud": {}, 324 | "kernelspec": { 325 | "display_name": "Python 3 (ipykernel)", 326 | "language": "python", 327 | "name": "python3" 328 | }, 329 | "language_info": { 330 | "codemirror_mode": { 331 | "name": "ipython", 332 | "version": 3 333 | }, 334 | "file_extension": ".py", 335 | "mimetype": "text/x-python", 336 | "name": "python", 337 | "nbconvert_exporter": "python", 338 | "pygments_lexer": "ipython3", 339 | "version": "3.8.13" 340 | } 341 | }, 342 | "nbformat": 4, 343 | "nbformat_minor": 4 344 | } 345 | --------------------------------------------------------------------------------