KWT-2024/lab/lab_09-10.ipynb

693 lines
43 KiB
Plaintext
Raw Permalink Normal View History

2024-04-13 08:20:53 +02:00
{
2024-06-10 22:42:57 +02:00
"cells": [
2024-04-13 08:20:53 +02:00
{
2024-06-10 22:42:57 +02:00
"cell_type": "markdown",
"id": "competitive-desire",
"metadata": {
"id": "competitive-desire"
},
"source": [
"![Logo 1](https://git.wmi.amu.edu.pl/AITech/Szablon/raw/branch/master/Logotyp_AITech1.jpg)\n",
"<div class=\"alert alert-block alert-info\">\n",
"<h1> Komputerowe wspomaganie tłumaczenia </h1>\n",
"<h2> 9,10. <i>Web scraping</i> [laboratoria]</h2>\n",
"<h3>Rafał Jaworski (2021)</h3>\n",
"</div>\n",
"\n",
"![Logo 2](https://git.wmi.amu.edu.pl/AITech/Szablon/raw/branch/master/Logotyp_AITech2.jpg)"
]
},
{
"cell_type": "markdown",
"id": "hungarian-davis",
"metadata": {
"id": "hungarian-davis"
},
"source": [
"Jak dobrze wiemy, w procesie wspomagania tłumaczenia oraz w zagadnieniach przetwarzania języka naturalnego ogromną rolę pełnią zasoby lingwistyczne. Należą do nich korpusy równoległe (pamięci tłumaczeń), korpusy jednojęzyczne oraz słowniki. Bywa, że zasoby te nie są dostępne dla języka, nad którym chcemy pracować."
]
},
{
"cell_type": "markdown",
"id": "featured-moisture",
"metadata": {
"id": "featured-moisture"
},
"source": [
"W tej sytuacji jest jeszcze dla nas ratunek - możemy skorzystać z zasobów dostępnych publicznie w Internecie. Na dzisiejszych zajęciach przećwiczymy techniki pobierania tekstu ze stron internetowych."
]
},
{
"cell_type": "markdown",
"id": "underlying-isaac",
"metadata": {
"id": "underlying-isaac"
},
"source": [
"Poniższy kod służy do ściągnięcia zawartości strony (w formacie HTML do zmiennej) oraz do wyszukania na tej stronie konkretnych elementów. Przed jego uruchomieniem należy zainstalować moduł BeautifulSoup:\n",
"`pip3 install beautifulsoup4`"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "revolutionary-trust",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "revolutionary-trust",
"outputId": "2d7cc0a5-506b-4e22-a1e3-07a3b7a025fc"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Autorska biżuteria od Goldenmark\n",
"Głośno na pl Wolności. \"Polskojęzyczny rząd i prokuratura plują na polski mundur\"\n",
"Ostatnia szansa na tak wysoką dotację w Poznaniu. \"Od 2025 r. będą one sukcesywnie spadać\"\n",
"Bardzo niebezpieczna roślina zaczęła kwitnąć. Jest ostrzeżenie!\n",
"Miasto z Wielkopolski wśród szesnastu Cudów Polski 2024. \"To wielka historia w małym mieście\"\n",
"Rapid Motocykle - najstarsza firma motocyklowa w Poznaniu zaprasza!\n",
"Kierowca Toyoty jechał pod prąd na S11. Zderzył się z motocyklem\n",
"Kilka masowych imprez w najbliższych dniach w Poznaniu. ZTM wprowadzi zmiany, na ulicach pojawi się nowa linia tramwajowa\n",
"Ekipa popularnego programu pojawiła się w Poznaniu. \"Będzie się działo\"\n",
"Poważny wypadek na krajowej \"jedenastce\". Kierowcy uwięzieni w busach\n",
"Wyjątkowa okazja, by zwiedzić to miejsce z przewodnikiem. \"Goście muszą mieć ukończone 7 lat i buty na płaskiej podeszwie\"\n",
"Najnowsze trendy edukacyjne - żłobek, przedszkole i szkoła w OGRODZIE\n",
"Kolejna inwestycja szykuje się na północy Poznania. \"Wybraliśmy wykonawcę\"\n",
"Zatrzaśnięta 2-latka w aucie na parkingu przy galerii handlowej. Wybito szybę\n",
"Pijany 19-latek rozbił kamieniem witraże w kościele i zerwał baner wyborczy. Jednej nocy\n",
"Korek na autostradowej obwodnicy Poznania. Zderzenie 3 aut\n",
"Rower dla nastolatka - wyzwanie dla rodzica\n",
"Co dalej ze śmigłowcem uszkodzonym na A2?\n",
"Coraz bardziej zaawansowane prace przy budowie Mostów Berdychowskich, kolejne zmiany w organizacji ruchu\n",
"W regionie powstaje największy park logistyczny w Polsce. Właśnie kończą przebudowywać drogi w okolicy na koszt inwestora\n",
"Dachował busem w rowie, prawdopodobnie zasnął. Poważny wypadek\n",
"Pijany wszedł na rusztowanie przy remontowanej wieży kościoła, bo chciał zrobić zdjęcie miasta z góry\n",
"Mieszkańcy skarżyli się na hałas generowany przez motocykle, 5 na 6 skontrolowanych z zatrzymanym dowodem rejestracyjnym\n",
"KODANO świętuje 20. urodziny! Promocje jakich jeszcze nie było!\n",
"Podpisano umowę na budowę kolejnej wielkopolskiej obwodnicy!\n",
"Akcja CBŚP pod Poznaniem. Zatrzymano jedną osobę\n",
"Sarna utknęła na szkolnym terenie\n",
"Na krajowej \"jedenastce\" bez zmian, wciąż gigantyczne korki przez remont mostu\n",
"Są oficjalne wyniki wyborów: 6 mandatów w Wielkopolsce! Jest jedno zaskoczenie\n",
"Brzegi Warty połączono ostatnim stalowym elementem Mostów Berdychowskich. Jest w nim kapsuła czasu z aktem erekcyjnym\n"
]
}
],
"source": [
"import requests\n",
"from bs4 import BeautifulSoup\n",
"\n",
"url='https://epoznan.pl'\n",
"\n",
"page = requests.get(url)\n",
"soup = BeautifulSoup(page.content, 'html.parser')\n",
"\n",
"headers = soup.find_all('h3', {'class':'postItem__title'})\n",
"\n",
"print('\\n'.join([header.get_text() for header in headers]))"
]
},
{
"cell_type": "markdown",
"id": "dental-combination",
"metadata": {
"id": "dental-combination"
},
"source": [
"### Ćwiczenie 1: Napisz funkcję do pobierania nazw towarów z serwisu Ceneo.pl. Typ towaru, np. telewizor, pralka, laptop jest parametrem funkcji. Wystarczy pobierać dane z pierwszej strony wyników wyszukiwania."
]
},
2024-04-13 08:20:53 +02:00
{
2024-06-10 22:42:57 +02:00
"cell_type": "markdown",
"source": [
"Ceneo.pl jest renderowane przez Javascript. Strona po requescie nie jest załadowana. W związku z tym, scrapowanie strony nie może odbyć się poprzez zwykła funkcję request, ponieważ w tym wypadku należy zasymulować przeglądarkę.\n",
"\n",
"\n",
"```\n",
"<!DOCTYPE html>\n",
"\n",
"<head>\n",
" <meta charset=\"utf-8\">\n",
" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n",
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n",
" \n",
" <script src=\"https://challenges.cloudflare.com/turnstile/v0/api.js\" async defer></script>\n",
"\n",
" <style>\n",
" html, body {\n",
" font-size: 13px;\n",
" font-family: Helvetica,Arial,Roboto,sans-serif;\n",
" line-height: 1.5;\n",
" color: #444;\n",
" background-color: #f2f5f7;\n",
" position: relative;\n",
" margin: 0;\n",
" padding: 0;\n",
" height: 100%;\n",
" }\n",
"\n",
" .footer {\n",
" padding-top: 20px;\n",
" position: absolute;\n",
" z-index: 5;\n",
" background-color: #f2f5f7;\n",
" bottom: 0;\n",
" width: 100%;\n",
" }\n",
"\n",
" .page-header .header-container {\n",
" position: relative;\n",
" background-color: #f2f5f7;\n",
" }\n",
"\n",
" .page-header .header-container > .wrapper {\n",
" display: -webkit-box;\n",
" display: -ms-flexbox;\n",
" display: flex;\n",
" height: 70px;\n",
" position: relative;\n",
" align-items: center;\n",
" }\n",
"\n",
" .main-content {\n",
" padding-bottom: 60px;\n",
" }\n",
"\n",
" .page-header .header-container .header-logo {\n",
" width: 220px;\n",
" }\n",
"\n",
" .ceneo-logo {\n",
" height: 53px;\n",
" display: inline-block;\n",
" vertical-align: top;\n",
" position: relative;\n",
" width: 116px;\n",
" margin: 0px 10px;\n",
" }\n",
"\n",
" .copyright {\n",
" margin-top: 1.5em;\n",
" text-align: center;\n",
" background: rgba(0,0,0,.1);\n",
" }\n",
"\n",
" .copyright .wrapper {\n",
" padding-top: .75em;\n",
" padding-bottom: .75em;\n",
" position: relative;\n",
" }\n",
"\n",
" a:active, a:hover {\n",
" outline: 0;\n",
" }\n",
"\n",
" a:hover {\n",
" color: #0071c5;\n",
" }\n",
"\n",
" a {\n",
" -webkit-transition: color .3s;\n",
" -moz-transition: color .3s;\n",
" -o-transition: color .3s;\n",
" transition: color .3s;\n",
" text-decoration: none;\n",
" color: #444;\n",
" }\n",
"\n",
" .layout_container {\n",
" min-height: 100%;\n",
" position: relative;\n",
" }\n",
"\n",
" .btn {\n",
" margin: 0;\n",
" display: inline-block;\n",
" padding: 5px 14px;\n",
" margin-bottom: 0;\n",
" font-size: 13px;\n",
" line-height: 19px;\n",
" text-align: center;\n",
" border-radius: 3px;\n",
" vertical-align: middle;\n",
" cursor: pointer;\n",
" -webkit-appearance: button;\n",
" font-family: sans-serif;\n",
" color: #fff;\n",
" border: 0;\n",
" border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);\n",
" background-color: #0071c5;\n",
" }\n",
"\n",
" .captcha-bot {\n",
" position: relative;\n",
" width: 352px;\n",
" margin: 10px auto;\n",
" text-align: center;\n",
" }\n",
"\n",
" @media (max-width: 960px) {\n",
" #bot {\n",
" display: none;\n",
" }\n",
" }\n",
" \n",
" .card-form {\n",
" box-shadow: 0 1px 3px rgba(0,0,0,.12), 0 1px 2px rgba(0,0,0,.24);\n",
" padding: 10px 25px!important;\n",
" box-sizing: border-box;\n",
" background-color: #fdfdfd;\n",
" }\n",
"\n",
" form {\n",
" margin: 0;\n",
" }\n",
"\n",
" #bot {\n",
" position: absolute;\n",
" right: -72px;\n",
" top: 0;\n",
" content: '';\n",
" width: 90px;\n",
" height: 155px;\n",
" }\n",
"\n",
" .card-form .col .col-wide {\n",
" width: 100%;\n",
" }\n",
" .captcha-bot .col-wide {\n",
" text-align: right;\n",
" margin: 15px 0;\n",
" }\n",
" .field-validation-error {\n",
" margin-bottom: .375em;\n",
" display: block;\n",
" border: 0;\n",
" color: #e71226\n",
" }\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"\n",
" <div id=\"layout_container\">\n",
" <header class=\"page-header\" role=\"banner\">\n",
" <div class=\"header-container\">\n",
" <div class=\"wrapper\">\n",
" <div class=\"header-logo\">\n",
" <span class=\"ceneo-logo\">\n",
" <a href=\"/\"><img src=\"https://www.ceneo.pl/Content/img/icons/logo-ceneo-simple-orange.svg\" alt=\"Ceneo - znajdź, porównaj, kup\"></a>\n",
" </span>\n",
" </div>\n",
" </div>\n",
" </div>\n",
" </header>\n",
"\n",
" <div class=\"main-content\">\n",
" <div class=\"wrapper\">\n",
" <div class=\"card-form captcha-bot\">\n",
" \n",
"\n",
"\n",
"<script type=\"text/javascript\">\n",
" function successChallengeCallback(token) {\n",
" var form = document.getElementById(\"turnstileChallenge\");\n",
" form.elements[\"client-side-errors\"].value = \"\";\n",
" form.submit();\n",
" }\n",
" function errorChallengeCallback(errorCode) {\n",
" var form = document.getElementById(\"turnstileChallenge\");\n",
" form.elements[\"client-side-errors\"].value = errorCode;\n",
" }\n",
"</script>\n",
"\n",
"<form id=\"turnstileChallenge\" method=\"post\" action=\"/Captcha/Add\">\n",
" <input hidden type=\"text\" id=\"ReturnUrl\" name=\"ReturnUrl\" value=\"%2fTelewizory\" />\n",
" <input hidden type=\"number\" id=\"CookieSeconds\" name=\"CookieSeconds\" value=\"172800\" />\n",
" <input hidden type=\"text\" id=\"CaptchaServiceProvider\" name=\"CaptchaServiceProvider\" value=\"Cloudflare\" />\n",
" <input type=\"hidden\" name=\"client-side-errors\"/>\n",
" <div class=\"cf-turnstile\" data-sitekey=\"0x4AAAAAAAUXnkfCYJAjoWMy\" data-callback=\"successChallengeCallback\" data-error-callback=\"errorChallengeCallback\" data-language=\"pl-pl\"></div>\n",
" <div class=\"col col-wide\">\n",
" <button type=\"submit\" class=\"btn btn-info\">Przejdź dalej</button>\n",
" </div>\n",
"</form>\n",
"\n",
"\n",
" <svg version=\"1.1\" id=\"bot\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\" viewBox=\"0 0 77 151.6\" style=\"enable-background: new 0 0 77 151.6;\" xml:space=\"preserve\"><style type=\"text/css\">.st0 {fill: #B55B28;}.st1 {fill: #F6921E;}.st2 {fill: #F1F1F2;}.st3 {fill: #1D427B;}.st4 {fill: #FFFFFF;}.st5 {fill: #BE222F;}.st6 {fill: #679B41;}.st7 {fill: #C43261;}.st8 {fill: none;stroke: #1D427B;stroke-width: 3;stroke-miterlimit: 10;}</style><g><rect x=\"14.3\" y=\"60.1\" transform=\"matrix(0.863 0.5053 -0.5053 0.863 35.5865 -4.3319)\" class=\"st0\" width=\"23\" height=\"6.7\"/><path class=\"st0\" d=\"M66.9,94.6l-33.5,53.6c-0.8,1.3-2.4,1.7-3.7,0.9l-17.2-10.1V59.5L66,90.8C67.3,91.6,67.7,93.3,66.9,94.6z\"/><path class=\"st1\" d=\"M50.5,85.1L17,138.6c-0.8,1.3-2.4,1.7-3.7,0.9l-0.8-0.5V59.5l37.1,21.7C50.9,82,51.3,83.7,50.5,85.1z\"/><path class=\"st2\" d=\"M46.6,85.8L15.8,135c-0.5,0.9-1.5,1.4-2.4,1.4c-0.3,0-0.6,0-0.9-0.2v-0.8c1,0.5,2.2,0.1,2.7-0.8L46,85.4c0.3-0.5,0.4-1.1,0.3-1.7c-0.1-0.6-0.5-1-1-1.3L12.5,63.2v-0.9l33.2,19.4c0.7,0.4,1.2,1,1.3,1.8C47.2,84.3,47,85.1,46.6,85.8z\"/><path class=\"st3\" d=\"M40.8,86.1l-17,25.9c-0.3,0.5-1,0.8-1.7,0.8c-0.6,0-1.3-0.2-1.9-0.6l-7.8-4.6V67l26.9,15.7c0.9,0.5,1.5,1.3,1.7,2C41.1,85.3,41,85.7,40.8,86.1z\"/><path class=\"st1\" d=\"M37.9,84.4l-16.9,26c-0.4,0.6-1.5,0.6-2.5,0l-6-3.5v-39l24.3,14.2C37.8,82.7,38.3,83.7,37.9,84.4z\"/><path class=\"st4\" d=\"M18.7,78c0,0-0.3,0.2-0.9,2.3c-0.5,1.7,0.1,4.5-1.5,7.8c-0.7,1.5-1.5,2.3-2.4,3c-0.1-0.1-0.1-0.2-0.3-0.2c-0.4-0.2-0.8-0.1-1.1,0.2v-2c0.3-0.3,0.6-0.8,0.9-1.2c0.7-1.3,1-2.4,0.9-3.3c-0.1-0.9-0.7-1.7-1.6-2.2c-0.1,0-0.1-0.1-0.2-0.1v-7.3L18.7,78z\"/><path class=\"st4\" d=\"M12.7,92.4c0.4,0.2,1,0.1,1.2-0.3c0.2-0.3,0.1-0.7-0.1-1c-0.5,0.4-0.9,0.7-1.4,1.1C12.5,92.3,12.6,92.3,12.7,92.4z\"/><path class=\"st4\" d=\"M19.8,90.7c-0.7-0.4-1.4-0.1-1.8,0c0.2-0.4,0.4-0.8,0.3-0.8c0,0-0.1,0-0.1,0l-0.8-0.1c-0.1,0-0.1,0-0.2,0c-0.1,0.1-0.1,0.3-0.2,0.5c-0.1,0.1-0.1,0.3-0.3,0.4l-3.6,3.9c0,0-0.1,0.1-0.1,0.2c0,0,0,0.1,0,0.1c0,0,0.1,0,0.1,0l0.8,0.3c0.1,0,0.2,0,0.2-0.1l1.2-1.3c0.1,0.2,0.2,0.4,0.6,0.6c1.4,0.8,3.2-0.6,3.9-1.9C20.5,91.6,20.4,91,19.8,90.7z M16.5,93.5c-0.3-0.2-0.4-0.4-0.4-0.5l1.1-1.2c0.5-0.5,1.2-1,1.7-0.7c0.3,0.2,0.3,0.4,0.1,0.8C18.4,92.9,17.3,94,16.5,93.5z\"/><path class=\"st4\" d=\"M24.2,91.2c0,0,0.1-0.1,0.1-0.2c0-0.1,0-0.1,0-0.1c0,0-0.1,0-0.1,0l-0.8-0.3c-0.1,0-0.2,0-0.2,0.1l-3.4,3.7c-0.2,0.3-0.4,0.5-0.6,0.8c-0.3,0.5-0.1,0.9,0.4,1.2c0.3,0.2,0.9,0.4,1,0.3c0,0,0-0.1,0-0.1l0.3-0.6c0-0.1,0-0.1,0-0.1c0,0-0.2,0-0.3-0.1c-0.1-0.1-0.2-0.2-0.1-0.3c0.1-0.1,0.2-0.3,0.4-0.5L24.2,91.2z\"/><path class=\"st4\" d=\"M19,118.4l-5.9,10c-0.2,0.3-0.4,0.5-0.7,0.7v-16.6l5.9,3.5C19.2,116.4,19.5,117.5,19,118.4z\"/><path class=\"st0\" d=\"M20.8,145.6l-3,5.2c-0.5,0.8-1.6,1.1-2.4,0.6l-2.9-1.7v-11.1l7.8,4.5C21.1,143.6,21.3,144.7,20.8,145.6z\"/><path class=\"st5\" d=\"M50.3,23.2l-7.2-3.4c-1.5-0.7-2.2-2.5-1.5-4.1l5.2-11.2c0.7-1.5,2.5-2.2,4.1-1.5l7.2,3.4c1.5,0.7,2.2,2.5,1.5,4.1l-5.2,11.2C53.7,23.2,51.9,23.9,50.3,23.2z\"/><path class=\"st0\" d=\"M76.5,30.9L57.4,72c-1.2,2.6-4.3,3.7-6.9,2.5l-38-17.7V36.7L26.1,7.4c1.2-2.6,4.3-3.7,6.9-2.5l41,19.1C76.6,25.3,77.7,28.3,76.5,30.9z\"/><path class=\"st1\" d=\"M67,26.5l-19.1,41c-1.2,2.6-4.3,3.7-6.9,2.5L12.5,56.7V11.9L16.6,3c1.2-2.6,4.3-3.7,6.9-2.5l41,19.1C67.1,20.8,68.2,23.9,67,26.5z\"/><ellipse transform=\"matrix(0.4228 -0.9062 0.9062 0.4228 -7.4003 89.152)\" class=\"st3\" cx=\"66.3\" cy=\"50.4\" rx=\"9.1\" ry=\"6.5\"/><path class=\"st1\" d=\"M69.7,52c0.7-1.5,3.3-2.1,3.3-2.1s-1-5.7-2.9-6.6c-2.6-1.2-6.2,1.1-8.1,5.2c-1.9,4.1-1.3,8.3,1.3,9.5c1.9,0.9,6.9-2,6.9-2S69,53.4,69.7,52z\"/><path class=\"st3\" d=\"M73,49.8c-1.3-0.2-2.7,0.7-3.3,2.1c-0.7,1.5-0.4,3.1,0.5,3.9c0.8-0.8,1.5-1.7,2-2.8C72.7,52,72.9,50.9,73,49.8z\"/><rect x=\"42\" y=\"12\" transform=\"matrix(0.9062 0.4228 -0.4228 0.9062 10.1025 -20.3141)\" class=\"st3\" width=\"17.8\" height=\"1.1\"/><path class=\"st0\" d=\"M27,36.5l-8.4-3.9c-0.3-0.1-0.4-0.5-0.3-0.8l7.6-16.2c0.1-0.3,0.5-0.4,0.8-0.3l8.4,3.9c0.3,0.1,0.4,0.5,0.3,0.8l-7
" </svg>\n",
" </div>\n",
" </div>\n",
" </div>\n",
"\n",
" <footer class=\"footer\">\n",
"\n",
" <div class=\"copyright\">\n",
" <div class=\"wrapper\">\n",
" © 2005-2024 Ceneo.pl sp. z o.o. Korzystanie z serwisu oznacza akceptację <a href=\"http://info.ceneo.pl/regulamin\" target=\"_blank\" title=\"Regulamin Ceneo.pl\">regulaminu</a>\n",
" </div>\n",
" </div>\n",
"\n",
" </footer>\n",
" </div>\n",
"\n",
"</body>\n",
"```\n",
"\n",
"\n"
],
"metadata": {
"id": "_gf6fTOWlyiB"
},
"id": "_gf6fTOWlyiB"
},
{
"cell_type": "code",
"execution_count": 16,
"id": "moving-clothing",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "moving-clothing",
"outputId": "1c861035-19ec-44af-d95c-66dd3e17f16d"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"https://www.ceneo.pl/Telewizory\n",
"[]\n",
"[]\n"
]
}
],
"source": [
"def get_names(article_type):\n",
" product_type_url = article_type.replace(' ', '+')\n",
" url = f'https://www.ceneo.pl/{product_type_url}'\n",
" print(url)\n",
"\n",
" headers = {\n",
" 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}\n",
"\n",
" response = requests.get(url, headers=headers)\n",
" if response.status_code != 200:\n",
" print(\"Failed to retrieve the page. Status code:\", response.status_code)\n",
" return []\n",
"\n",
" soup = BeautifulSoup(response.text, 'html.parser')\n",
" products = soup.find_all('div', class_='cat-prod-row__body')\n",
" print(products)\n",
" product_names = []\n",
" for product in products:\n",
" name = product.find('a', class_='go-to-product').get_text(strip=True)\n",
" product_names.append(name)\n",
"\n",
" return product_names\n",
"\n",
"product_type = \"Telewizory\"\n",
"names = get_names(product_type)\n",
"print(names)"
]
},
{
"cell_type": "markdown",
"id": "mechanical-produce",
"metadata": {
"id": "mechanical-produce"
},
"source": [
"W ten sposób pobieramy dane z jednej strony. Nic jednak nie stoi nam na przeszkodzie, aby zasymulować przełączanie stron."
]
},
{
"cell_type": "markdown",
"id": "legitimate-corrections",
"metadata": {
"id": "legitimate-corrections"
},
"source": [
"### Ćwiczenie 2: Zaobserwuj, jak zmienia się url strony podczas przechodzenia do kolejnych stron wyników wyszukiwania na Ceneo.pl. Wykorzystaj tę informację i uruchom funkcję get_names() na więcej niż jednej stronie wyników."
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "german-dispute",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "german-dispute",
"outputId": "1f748364-00e3-4aec-95d4-61f38dbe43ea"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"https://www.ceneo.pl/Telewizory\n",
"[]\n",
"https://www.ceneo.pl/Telewizory;0020-30-0-0-1.htm\n",
"[]\n",
"https://www.ceneo.pl/Telewizory;0020-30-0-0-2.htm\n",
"[]\n",
"https://www.ceneo.pl/Telewizory;0020-30-0-0-3.htm\n",
"[]\n",
"https://www.ceneo.pl/Telewizory;0020-30-0-0-4.htm\n",
"[]\n",
"https://www.ceneo.pl/Telewizory;0020-30-0-0-5.htm\n",
"[]\n",
"https://www.ceneo.pl/Telewizory;0020-30-0-0-6.htm\n",
"[]\n",
"https://www.ceneo.pl/Telewizory;0020-30-0-0-7.htm\n",
"[]\n",
"https://www.ceneo.pl/Telewizory;0020-30-0-0-8.htm\n",
"[]\n",
"https://www.ceneo.pl/Telewizory;0020-30-0-0-9.htm\n",
"[]\n",
"[[], [], [], [], [], [], [], [], [], []]\n"
]
}
],
"source": [
"def scrape_names(name, pages):\n",
" return [get_names(name if i == 0 else f'{name};0020-30-0-0-{i}.htm') for i in range(pages)]\n",
"\n",
"names_from_pages = scrape_names(product_type, 10)\n",
"print(names_from_pages)"
]
},
{
"cell_type": "markdown",
"id": "discrete-durham",
"metadata": {
"id": "discrete-durham"
},
"source": [
"Technika pobierania treści z Internetu jest szczególnie efektywnym sposobem na pozyskiwanie dużych ilości tekstu. Poniższy fragment kodu służy do ściągnięcia całości tekstu ze strony."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "premium-button",
"metadata": {
"id": "premium-button",
"outputId": "3254fe70-46a5-4392-eca6-53e8d5c8dd26"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" Yahoo Make Yahoo Your HomepageDiscover something new every day from News, Sports, Finance, Entertainment and more! HOME MAIL NEWS FINANCE SPORTS ENTERTAINMENT LIFE SHOPPING YAHOO PLUS MORE... Download the Yahoo Home app Yahoo Home Search query Sign in Mail Sign in to view your mail Mail Mail COVID-19 COVID-19 News News Finance Finance Sports Sports Entertainment Entertainment Life Life Shopping Shopping Yahoo Plus Yahoo Plus More... More... Follow live:Closing arguments begin for Derek Chauvin's murder trial in the death of George Floyd 5 people in hospital after shooting in Louisiana One victim was shot in the head, and another suffered multiple gunshot wounds, according to local news outlet.Multiple police units dispatched to scene »2 dead in crash of Tesla with 'no one' drivingMall shooter, 16, faces 1st-degree murder charge'80s pop star rips 'Simpsons' for 'hateful' parodyConspiracy theorist Alex Jones faces a reckoningPig's head left at former home of Chauvin trial witness U.S.HuffPostFirst-Ever Wild Wolf Collar Camera Shows What They Really Do All Day LongThis canine's favorite meal might surprise you. Thanks for your feedback! CelebrityThe TelegraphRobert De Niro unable to turn down acting roles because of his estranged wife's expensive lifestyleHollywood legend Robert De Niro is unable to turn down acting roles because he must pay for his estranged wife's expensive tastes, the actor's lawyer has claimed. Caroline Krauss told a Manhattan court that he is struggling financially because of the pandemic, a massive tax bill and the demands of Grace Hightower, who filed for divorce in 2018 after 21 years of marriage. The court has been asked to settle how much De Niro should pay Ms Hightower, 66, until the terms of the prenuptial agreement the couple negotiated in 2004 takes effect. “Mr De Niro is 77 years old, and while he loves his craft, he should not be forced to work at this prodigious pace because he has to,” Ms Krauss told the court. “When does that stop? When does he get the opportunity to not take every project that comes along and not work six-day weeks, 12-hour days so he can keep pace with Ms Hightowers thirst for Stella McCartney?” Thanks for your feedback! U.S.Associated PressCouple: Man has tossed used cups in their yard for 3 yearsAn upstate New York couple may have finally solved the mystery of who's been tossing used coffee cups in their front yard for nearly three years. Edward and Cheryl Patton told The Buffalo News they tried mounting a camera in a tree in front of their home in Lake View to catch the phantom litterer. After Edward Patton called police, they waited and pulled over a vehicle driven by 76-year-old Larry Pope, who Cheryl Patton said had once worked with her and had had disagreements with her over union issues. Thanks for your feedback! U.S.INSIDERA leading conspiracy theorist who thought COVID-19 was a hoax died from the virus after hosting illegal house partiesA high-profile conspiracy theorist from Norway, who shared false information about the pandemic online, has died from COVID-19, officials say. Thanks for your feedback! PoliticsThe WeekOne America News Network producer says 'majority' of employees didn't believe reports on voter fraud claimsMarty Golingan, a producer at One America News Network, a right-wing cable news channel often noted for its affinity for former President Donald Trump, told The New York Times he was worried his work may have helped inspire the Jan. 6 Capitol riot. At one point during the incident, Golingan said he caught sight of someone in the mob holding a flag with OAN's logo. \"I was like, OK, that's not good. That's what happens when people listen to us,\" he told the Times, referring to OAN's coverage of the 2020 presidential election, which often gave credence to Trump's unfounded claims of widespread voter fraud and Democratic conspiracies. Golingan said that many of his colleagues, including himself, disagreed with the coverage. \"The majority of people did not believe the voter fraud claims being run on the air,\"
]
}
],
"source": [
"import re\n",
"\n",
"url = \"https://www.yahoo.com\"\n",
"\n",
"page = requests.get(url)\n",
"soup = BeautifulSoup(page.content, 'html.parser')\n",
"\n",
"# usunięcie elementów script i style\n",
"for script in soup([\"script\", \"style\"]):\n",
" script.extract() # usuń element\n",
"\n",
"# pobierz tekst\n",
"text = soup.get_text()\n",
"\n",
"# usuń wielokrotne białe znaki\n",
"text = re.sub(r\"\\s+\", \" \", text)\n",
"\n",
"print(text)"
]
},
{
"cell_type": "markdown",
"id": "assigned-necessity",
"metadata": {
"id": "assigned-necessity"
},
"source": [
"### Ćwiczenie 3: Napisz program do pobrania tekstu ze strony Wydziału Matematyki i Informatyki. Pobierz cały tekst ze strony głównej a następnie wyszukaj na tej stronie wszystkich linków wewnętrznych i pobierz tekst ze stron wskazywanych przez te linki. Nie zagłębiaj się już dalej.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "regulation-sheriff",
"metadata": {
"id": "regulation-sheriff"
},
"outputs": [],
"source": [
"import requests\n",
"from bs4 import BeautifulSoup\n",
"import re\n",
"\n",
"def get_page_text(url):\n",
" page = requests.get(url)\n",
" soup = BeautifulSoup(page.content, 'html.parser')\n",
"\n",
" for script in soup([\"script\", \"style\"]):\n",
" script.extract()\n",
"\n",
" text = soup.get_text()\n",
" text = re.sub(r\"\\s+\", \" \", text) # white chars removal\n",
"\n",
" return text\n",
"\n",
"def get_internal_links(url, domain):\n",
" page = requests.get(url)\n",
" soup = BeautifulSoup(page.content, 'html.parser')\n",
"\n",
" links = soup.find_all('a', href=True)\n",
" return [link['href'] for link in links if domain in link['href']]\n",
"\n",
"def scrape_wmi():\n",
" base_url = \"https://wmi.amu.edu.pl/\"\n",
"\n",
" main_text = get_page_text(base_url)\n",
" print(\"Tekst ze strony głównej:\\n\", main_text[:1000], \"...\")\n",
" internal_links = list(set(get_internal_links(base_url, \"wmi.amu.edu.pl\")))\n",
"\n",
" return [get_page_text(base_url + link if link.startswith('/') else link) for link in internal_links]\n",
"\n",
"\n",
"scrape_wmi()"
]
},
{
"cell_type": "markdown",
"id": "paperback-hello",
"metadata": {
"id": "paperback-hello"
},
"source": [
"Omówione wyżej techniki działają również bardzo dobrze dla zasobów słownikowych."
]
},
{
"cell_type": "markdown",
"id": "after-activity",
"metadata": {
"id": "after-activity"
},
"source": [
"### Ćwiczenie 4: Pobierz jak najwięcej słów w języku albańskim z serwisu glosbe.com."
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "surgical-ozone",
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "surgical-ozone",
"outputId": "17e333b1-c429-4d03-e2de-773655c4b88d"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Słowa ze strony głównej:\n",
" ['tungjatjeta', 'lakmitar', 'lakmitar', 'zbret', 'naten e mirë', 'bir kurvë']\n",
"Wszystkie słowa: ['lakmitar', 'naten e mirë', 'zbret', 'tungjatjeta', 'bir kurvë']\n"
]
}
],
"source": [
"def get_page_words(url):\n",
" page = requests.get(url)\n",
" soup = BeautifulSoup(page.content, 'html.parser')\n",
"\n",
" # Pobierz wszystkie słowa ze strony\n",
" words = []\n",
" prefix = '/sq/pl'\n",
" for word in soup.find_all('a', href=True):\n",
" if word['href'].startswith(prefix):\n",
" text = word.get_text().replace(prefix, '').replace('\\n', '')\n",
" if len(text) > 0:\n",
" words.append(text)\n",
"\n",
" return words\n",
"\n",
"def scrape_shqip():\n",
" base_url = \"https://glosbe.com/pl/sq/\"\n",
" domain = \"glosbe.com\"\n",
"\n",
" # Pobierz słowa ze strony głównej\n",
" words = get_page_words(base_url)\n",
" print(\"Słowa ze strony głównej:\\n\", words)\n",
" # Usuń duplikaty\n",
" words = list(set(words))\n",
" print(\"Wszystkie słowa:\", words)\n",
"\n",
"\n",
"scrape_shqip()"
]
}
],
"metadata": {
"author": "Rafał Jaworski",
"email": "rjawor@amu.edu.pl",
"lang": "pl",
"subtitle": "9,10. Web scraping",
"title": "Komputerowe wspomaganie tłumaczenia",
"year": "2021",
"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.8.10"
},
"colab": {
"provenance": []
2024-04-13 08:20:53 +02:00
}
},
2024-06-10 22:42:57 +02:00
"nbformat": 4,
"nbformat_minor": 5
}