{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "___\n", "\n", " \n", " \n", "
\n", "
\n", " \n", "
Content Copyright by Pierian Data and xDM Consulting
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercices de Web Scraping \n", "\n", "## Réalisez les tâches suivantes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Tâche : Importer toutes les bibliothèques que vous pensez nécessaires pour \"scraper\" un site Web**" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# VOTRE CODE ICI" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import requests\n", "import bs4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Tâche : Utiliser les bibliothèques requests et BeautifulSoup pour vous connecter à http://quotes.toscrape.com/ et lire le code HMTL de la page de garde**" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# VOTRE CODE ICI" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "res = requests.get(\"http://quotes.toscrape.com/\")" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\\n\\n\\n\\t\\n\\tQuotes to Scrape\\n \\n \\n\\n\\n
\\n
\\n
\\n

\\n Quotes to Scrape\\n

\\n
\\n
\\n

\\n \\n Login\\n \\n

\\n
\\n
\\n \\n\\n
\\n
\\n\\n
\\n “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”\\n by Albert Einstein\\n (about)\\n \\n
\\n Tags:\\n \\n \\n change\\n \\n deep-thoughts\\n \\n thinking\\n \\n world\\n \\n
\\n
\\n\\n
\\n “It is our choices, Harry, that show what we truly are, far more than our abilities.”\\n by J.K. Rowling\\n (about)\\n \\n
\\n Tags:\\n \\n \\n abilities\\n \\n choices\\n \\n
\\n
\\n\\n
\\n “There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”\\n by Albert Einstein\\n (about)\\n \\n
\\n Tags:\\n \\n \\n inspirational\\n \\n life\\n \\n live\\n \\n miracle\\n \\n miracles\\n \\n
\\n
\\n\\n
\\n “The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”\\n by Jane Austen\\n (about)\\n \\n
\\n Tags:\\n \\n \\n aliteracy\\n \\n books\\n \\n classic\\n \\n humor\\n \\n
\\n
\\n\\n
\\n “Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.”\\n by Marilyn Monroe\\n (about)\\n \\n
\\n Tags:\\n \\n \\n be-yourself\\n \\n inspirational\\n \\n
\\n
\\n\\n
\\n “Try not to become a man of success. Rather become a man of value.”\\n by Albert Einstein\\n (about)\\n \\n
\\n Tags:\\n \\n \\n adulthood\\n \\n success\\n \\n value\\n \\n
\\n
\\n\\n
\\n “It is better to be hated for what you are than to be loved for what you are not.”\\n by André Gide\\n (about)\\n \\n
\\n Tags:\\n \\n \\n life\\n \\n love\\n \\n
\\n
\\n\\n
\\n “I have not failed. I've just found 10,000 ways that won't work.”\\n by Thomas A. Edison\\n (about)\\n \\n
\\n Tags:\\n \\n \\n edison\\n \\n failure\\n \\n inspirational\\n \\n paraphrased\\n \\n
\\n
\\n\\n
\\n “A woman is like a tea bag; you never know how strong it is until it's in hot water.”\\n by Eleanor Roosevelt\\n (about)\\n \\n
\\n Tags:\\n \\n \\n misattributed-eleanor-roosevelt\\n \\n
\\n
\\n\\n
\\n “A day without sunshine is like, you know, night.”\\n by Steve Martin\\n (about)\\n \\n
\\n Tags:\\n \\n \\n humor\\n \\n obvious\\n \\n simile\\n \\n
\\n
\\n\\n \\n
\\n
\\n \\n

Top Ten tags

\\n \\n \\n love\\n \\n \\n \\n inspirational\\n \\n \\n \\n life\\n \\n \\n \\n humor\\n \\n \\n \\n books\\n \\n \\n \\n reading\\n \\n \\n \\n friendship\\n \\n \\n \\n friends\\n \\n \\n \\n truth\\n \\n \\n \\n simile\\n \\n \\n \\n
\\n
\\n\\n
\\n \\n\\n'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "res.text" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Tâche : Récupérer tous les noms des auteurs de la première page**" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "# VOTRE CODE ICI" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "soupe = bs4.BeautifulSoup(res.text,'lxml')" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[Albert Einstein,\n", " J.K. Rowling,\n", " Albert Einstein,\n", " Jane Austen,\n", " Marilyn Monroe,\n", " Albert Einstein,\n", " André Gide,\n", " Thomas A. Edison,\n", " Eleanor Roosevelt,\n", " Steve Martin]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "soupe.select(\".author\")" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "# Le set permet d'éliminer les doublons\n", "auteurs = set() \n", "for nom in soupe.select(\".author\"):\n", " auteurs.add(nom.text)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Albert Einstein',\n", " 'André Gide',\n", " 'Eleanor Roosevelt',\n", " 'J.K. Rowling',\n", " 'Jane Austen',\n", " 'Marilyn Monroe',\n", " 'Steve Martin',\n", " 'Thomas A. Edison'}" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "auteurs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Tâche : Créer une liste de toutes les citations sur la première page**" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "# VOTRE CODE ICI" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "citations = []\n", "for citation in soupe.select(\".text\"):\n", " citations.append(citation.text)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”',\n", " '“It is our choices, Harry, that show what we truly are, far more than our abilities.”',\n", " '“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”',\n", " '“The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.”',\n", " \"“Imperfection is beauty, madness is genius and it's better to be absolutely ridiculous than absolutely boring.”\",\n", " '“Try not to become a man of success. Rather become a man of value.”',\n", " '“It is better to be hated for what you are than to be loved for what you are not.”',\n", " \"“I have not failed. I've just found 10,000 ways that won't work.”\",\n", " \"“A woman is like a tea bag; you never know how strong it is until it's in hot water.”\",\n", " '“A day without sunshine is like, you know, night.”']" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "citations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Tâche : inspecter le site et utiliser Beautiful Soup pour extraire les 10 premiers Tags afichés en haut et à droite de la page d'accueil (par.ex. Love,Inspirational,Life, etc...). \n", "INDICE : cherchez le marqueur qui se cache derrière chaque citation, essayer d'identifier une classe uniquement présente en haut à droite de la page, cherchez ausssi du côté du span**" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "# VOTRE CODE ICI" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "soupe = bs4.BeautifulSoup(res.text,'lxml')" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[\n", " love\n", " ,\n", " \n", " inspirational\n", " ,\n", " \n", " life\n", " ,\n", " \n", " humor\n", " ,\n", " \n", " books\n", " ,\n", " \n", " reading\n", " ,\n", " \n", " friendship\n", " ,\n", " \n", " friends\n", " ,\n", " \n", " truth\n", " ,\n", " \n", " simile\n", " ]" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "soupe.select('.tag-item')" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "love\n", "\n", "\n", "inspirational\n", "\n", "\n", "life\n", "\n", "\n", "humor\n", "\n", "\n", "books\n", "\n", "\n", "reading\n", "\n", "\n", "friendship\n", "\n", "\n", "friends\n", "\n", "\n", "truth\n", "\n", "\n", "simile\n", "\n" ] } ], "source": [ "for item in soupe.select(\".tag-item\"):\n", " print(item.text)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Tâche: Remarquez qu'il y a plus d'une page et que les pages suivantes ressemblent à ceci http://quotes.toscrape.com/page/2/. Utilisez ce que vous savez sur les boucles for et la concaténation de chaînes pour parcourir toutes les pages et obtenir la liste des auteurs présents sur le site Web. Gardez à l'esprit qu'il existe de nombreuses façons d'y parvenir, notez également que vous devrez d'une manière ou d'une autre déterminer comment vérifier que votre boucle est sur la dernière page avec des citations. À des fins de débogage, je vous fait remarquer qu'il n'y a que 10 pages, donc la dernière est http://quotes.toscrape.com/page/10/, mais essayez de créer une boucle suffisamment robuste pour qu'elle n'aie pas besoin de connaître le nombre de pages à l'avance, vous pouvez par exemple utiliser try/except pour cela. C'est à vous de jouer !**" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "# VOTRE CODE ICI" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Première solution\n", "Supposant que l'on connait le nombre de pages à lire\n" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "url = 'http://quotes.toscrape.com/page/'" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "auteurs = set()\n", "\n", "for page in range(1,10):\n", "\n", " # Concatenate to get new page URL\n", " url_page = url+str(page)\n", " # Obtain Request\n", " res = requests.get(url_page)\n", " # Turn into Soup\n", " soupe = bs4.BeautifulSoup(res.text,'lxml')\n", " # Add Authors to our set\n", " for nom in soupe.select(\".author\"):\n", " auteurs.add(nom.text)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Albert Einstein',\n", " 'Alexandre Dumas fils',\n", " 'Alfred Tennyson',\n", " 'Allen Saunders',\n", " 'André Gide',\n", " 'Ayn Rand',\n", " 'Bob Marley',\n", " 'C.S. Lewis',\n", " 'Charles Bukowski',\n", " 'Charles M. Schulz',\n", " 'Douglas Adams',\n", " 'Dr. Seuss',\n", " 'Eleanor Roosevelt',\n", " 'Elie Wiesel',\n", " 'Ernest Hemingway',\n", " 'Friedrich Nietzsche',\n", " 'Garrison Keillor',\n", " 'George Bernard Shaw',\n", " 'George Carlin',\n", " 'George Eliot',\n", " 'George R.R. Martin',\n", " 'Haruki Murakami',\n", " 'Helen Keller',\n", " 'J.D. Salinger',\n", " 'J.K. Rowling',\n", " 'J.R.R. Tolkien',\n", " 'James Baldwin',\n", " 'Jane Austen',\n", " 'Jim Henson',\n", " 'John Lennon',\n", " 'Jorge Luis Borges',\n", " 'Marilyn Monroe',\n", " 'Mark Twain',\n", " 'Martin Luther King Jr.',\n", " 'Mother Teresa',\n", " 'Pablo Neruda',\n", " 'Ralph Waldo Emerson',\n", " 'Stephenie Meyer',\n", " 'Steve Martin',\n", " 'Suzanne Collins',\n", " 'Terry Pratchett',\n", " 'Thomas A. Edison',\n", " 'W.C. Fields',\n", " 'William Nicholson'}" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "auteurs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Deuxième solution\n", "On ne connait pas le nombre de pages, mais on connait la dernière" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Jetons un œil sur ce qui se passe quand on dépasse la dernière page" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "# On prend un numéro de page trop gros pour exister\n", "url_page = url+str(9999999)\n", "\n", "# Obtain Request\n", "res = requests.get(url_page)\n", "\n", "# Turn into Soup\n", "soupe = bs4.BeautifulSoup(res.text,'lxml')" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\n", "\n", "\n", "\n", "Quotes to Scrape\n", "\n", "\n", "\n", "\n", "
\n", "
\n", "
\n", "

\n", "Quotes to Scrape\n", "

\n", "
\n", "
\n", "

\n", "Login\n", "

\n", "
\n", "
\n", "
\n", "
\n", "\n", "No quotes found!\n", "\n", " \n", "
\n", "
\n", "

Top Ten tags

\n", "\n", "love\n", "\n", "\n", "inspirational\n", "\n", "\n", "life\n", "\n", "\n", "humor\n", "\n", "\n", "books\n", "\n", "\n", "reading\n", "\n", "\n", "friendship\n", "\n", "\n", "friends\n", "\n", "\n", "truth\n", "\n", "\n", "simile\n", "\n", "
\n", "
\n", "
\n", "\n", "\n", "" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "soupe" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Cette solution demande à ce que la chaine de caractères \"No quotes found!\" \n", "# ne soit présente que sur la dernière page\n", "# Si pour une raison quelconque cette chaine se trouvait sur d'autres pages, \n", "# il faudrait faire une recherche plus détaillée\n", "\"No quotes found!\" in res.text" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "page_valide = True\n", "auteurs = set()\n", "page = 1\n", "\n", "while page_valide:\n", "\n", " # Concatenate to get new page URL\n", " url_page = url+str(page)\n", " \n", " # Obtain Request\n", " res = requests.get(url_page)\n", " \n", " # Check to see if we're on the last page\n", " if \"No quotes found!\" in res.text:\n", " break\n", " \n", " # Turn into Soup\n", " soupe = bs4.BeautifulSoup(res.text,'lxml')\n", " \n", " # Add Authors to our set\n", " for nom in soupe.select(\".author\"):\n", " auteurs.add(nom.text)\n", " \n", " # Go to Next Page\n", " page += 1" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Albert Einstein',\n", " 'Alexandre Dumas fils',\n", " 'Alfred Tennyson',\n", " 'Allen Saunders',\n", " 'André Gide',\n", " 'Ayn Rand',\n", " 'Bob Marley',\n", " 'C.S. Lewis',\n", " 'Charles Bukowski',\n", " 'Charles M. Schulz',\n", " 'Douglas Adams',\n", " 'Dr. Seuss',\n", " 'E.E. Cummings',\n", " 'Eleanor Roosevelt',\n", " 'Elie Wiesel',\n", " 'Ernest Hemingway',\n", " 'Friedrich Nietzsche',\n", " 'Garrison Keillor',\n", " 'George Bernard Shaw',\n", " 'George Carlin',\n", " 'George Eliot',\n", " 'George R.R. Martin',\n", " 'Harper Lee',\n", " 'Haruki Murakami',\n", " 'Helen Keller',\n", " 'J.D. Salinger',\n", " 'J.K. Rowling',\n", " 'J.M. Barrie',\n", " 'J.R.R. Tolkien',\n", " 'James Baldwin',\n", " 'Jane Austen',\n", " 'Jim Henson',\n", " 'Jimi Hendrix',\n", " 'John Lennon',\n", " 'Jorge Luis Borges',\n", " 'Khaled Hosseini',\n", " \"Madeleine L'Engle\",\n", " 'Marilyn Monroe',\n", " 'Mark Twain',\n", " 'Martin Luther King Jr.',\n", " 'Mother Teresa',\n", " 'Pablo Neruda',\n", " 'Ralph Waldo Emerson',\n", " 'Stephenie Meyer',\n", " 'Steve Martin',\n", " 'Suzanne Collins',\n", " 'Terry Pratchett',\n", " 'Thomas A. Edison',\n", " 'W.C. Fields',\n", " 'William Nicholson'}" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "auteurs" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Albert Einstein',\n", " 'Alexandre Dumas fils',\n", " 'Alfred Tennyson',\n", " 'Allen Saunders',\n", " 'André Gide',\n", " 'Ayn Rand',\n", " 'Bob Marley',\n", " 'C.S. Lewis',\n", " 'Charles Bukowski',\n", " 'Charles M. Schulz',\n", " 'Douglas Adams',\n", " 'Dr. Seuss',\n", " 'E.E. Cummings',\n", " 'Eleanor Roosevelt',\n", " 'Elie Wiesel',\n", " 'Ernest Hemingway',\n", " 'Friedrich Nietzsche',\n", " 'Garrison Keillor',\n", " 'George Bernard Shaw',\n", " 'George Carlin',\n", " 'George Eliot',\n", " 'George R.R. Martin',\n", " 'Harper Lee',\n", " 'Haruki Murakami',\n", " 'Helen Keller',\n", " 'J.D. Salinger',\n", " 'J.K. Rowling',\n", " 'J.M. Barrie',\n", " 'J.R.R. Tolkien',\n", " 'James Baldwin',\n", " 'Jane Austen',\n", " 'Jim Henson',\n", " 'Jimi Hendrix',\n", " 'John Lennon',\n", " 'Jorge Luis Borges',\n", " 'Khaled Hosseini',\n", " \"Madeleine L'Engle\",\n", " 'Marilyn Monroe',\n", " 'Mark Twain',\n", " 'Martin Luther King Jr.',\n", " 'Mother Teresa',\n", " 'Pablo Neruda',\n", " 'Ralph Waldo Emerson',\n", " 'Stephenie Meyer',\n", " 'Steve Martin',\n", " 'Suzanne Collins',\n", " 'Terry Pratchett',\n", " 'Thomas A. Edison',\n", " 'W.C. Fields',\n", " 'William Nicholson'}" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "page_valide = True\n", "auteurs = set()\n", "page = 1\n", "url = 'http://quotes.toscrape.com/page/'\n", "\n", "while page_valide:\n", " \n", " url_page = url+str(page)\n", " res = requests.get(url_page)\n", " \n", " if \"No quotes found!\" in res.text:\n", " page_valide = False\n", " else:\n", " soupe = bs4.BeautifulSoup(res.text, 'lxml')\n", "\n", " for nom in soupe.select(\".author\"):\n", " auteurs.add(nom.text)\n", "\n", " page += 1\n", " \n", "\n", "auteurs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Il existe de nombreuses autres solutions potentielles qui pourraient être plus robustes et flexibles, l'idée principale est la même, utilisez une boucle while pour parcourir les pages potentielles et avoir une condition de rupture basée sur la page invalide." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.7" } }, "nbformat": 4, "nbformat_minor": 2 }