<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muhammad Naufal Hanif on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Naufal Hanif on Medium]]></description>
        <link>https://medium.com/@naufaltechhub?source=rss-1ea0ae4711e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0ioUSKfAqKm3ibWLxK-k2g.jpeg</url>
            <title>Stories by Muhammad Naufal Hanif on Medium</title>
            <link>https://medium.com/@naufaltechhub?source=rss-1ea0ae4711e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:30:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@naufaltechhub/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[1 Kalimat yang Menghancurkan Interview Gw — dan 7 Pelajaran Brutal Tentang First Impression di…]]></title>
            <link>https://naufaltechhub.medium.com/1-kalimat-yang-menghancurkan-interview-gw-dan-7-pelajaran-brutal-tentang-first-impression-di-29f99aa183a3?source=rss-1ea0ae4711e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/29f99aa183a3</guid>
            <dc:creator><![CDATA[Muhammad Naufal Hanif]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 04:14:44 GMT</pubDate>
            <atom:updated>2026-04-29T05:36:58.397Z</atom:updated>
            <content:encoded><![CDATA[<h3>1 Kalimat yang Menghancurkan Interview Gw — dan 7 Pelajaran Brutal Tentang First Impression di Dunia Kerja</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fEu-2gg8rIH3xPsr3cRyQ.png" /></figure><p>Ada momen dalam hidup yang hanya perlu <strong>1 kalimat</strong> untuk mengubah arah cerita.</p><blockquote>Bukan karena lu nggak capable.<br>Bukan karena lu nggak cukup pintar.<br>Tapi karena… timing dan persepsi orang lain.</blockquote><blockquote>Karena gw baru aja ngalamin hal itu..</blockquote><h4>Awalnya Semua Terasa “Aman &amp; Lancar”</h4><p>Interview berjalan lancar.<br>Obrolan ngalir.<br>Ngga ada tanda-tanda red flag; semua terasa aman.</p><p>Bahkan setelah itu, HR outsource kasih kabar:</p><blockquote>Overall sih udah oke, qualified dan melebihi expectation.</blockquote><p>Kalimat yang bikin tenang dan bangga sama diri sendiri.<br>Harusnya ini jadi nilai plus.<br><strong>Harusnya..</strong></p><h4>Lalu Datang 1 Kalimat Itu</h4><p>Di tengah interview, gw sempat bilang sesuatu yang menurut gw <em>jujur</em> dan <em>realistis</em>:</p><blockquote>Saya bisa cepet masuk tapi sambil double job saat periode 1 month notice resign</blockquote><p>Yang terpikir di otak gw saat itu:<br> — Ini bentuk transparansi<br> — Ini bukti fleksibilitas</p><p>Di kepala mereka?</p><blockquote>Risk.</blockquote><p>Selesai.</p><h4>Dunia Kerja Itu Ngga Selalu Tentang Fakta</h4><p>Ini bagian yang pait.</p><blockquote>Ada konsep di psikologi yang namanya <em>primary-effect — </em>di mana <strong>informasi pertama yang kita sampaikan punya pengaruh paling besar dalam membentuk penilaian orang lain</strong>.</blockquote><p>Artinya?</p><p>Kalimat pertama lu… bukan cuman pembuka.<br>Tapi bisa jadi penentu arah penilaian mereka selanjutnya.</p><blockquote>Ditambah lagi, ada penelitian soal <em>thin slicing</em> (Ambady &amp; Rosenthal) yang nunjukin kalau <strong>manusia bisa membentuk penilaian hanya dalam beberapa menit pertama interaksi.</strong></blockquote><p>Jadi,<br> — Mereka belum kenal lu sepenuhnya<br> — Mereka belum lihat semua kemampuan lu<br> — Tapi “Feeling” mereka… sudah mulai terbentuk</p><p>Dan yang lebih brutal:</p><blockquote>Orang ngga menilai niat lu.<br>Mereka menilai <strong>arti dari kata-kata lu — versi mereka sendiri.</strong></blockquote><p>Begitu satu persepsi kebentuk, otak mereka akan secara otomatis mencari pembenaran.<br>Dan di kasus gw…<br><strong>Satu kalimat soal <em>double job</em> itu cukup untuk jadi “label”.</strong></p><h4>Kenapa Ini Ngena Banget?</h4><p>Karena sebenarnya…<br>Gw adalah orang yang:<br> — <strong>Setia kalau sudah commit</strong><br> — <strong>Menjunjung tinggi peraturan</strong><br> — <strong>Ngga masalah melepaskan yang lain demi fokus</strong></p><p>Tapi itu semua… <strong>ngga sempat “terlihat” dengan kuat.<br></strong>Yang tinggal cuman satu frame:</p><blockquote>Orang ini biasa double job</blockquote><p>Dan dalam konteks perusahaan — apalagi yang butuh reliability tinggi — itu udah sangat cukup untuk bikin mereka mundur.</p><h4>Rasanya? Jujur Aja: Hancur</h4><p>Ada fase di mana gw:<br> — Menyesal disetiap detiknya<br> — Overthinking<br> — Replay kejadian interview itu diotak gw berulang kali<br> — Berandai-andai “Andaikan gw ga ngomong kaya gitu..” dsb.</p><p>Dan ujungnya satu:</p><blockquote><strong>“Gw Gagal.”</strong></blockquote><p>Padahal logikanya ngga sesederhana itu.</p><h4>Ini Bukan Tentang Satu Interview</h4><p>Kalau lu ada diposisi yang sama kaya gw, berusaha untuk bertahan hidup diindonesia, lu pasti sangat ngerti, kalau:</p><ul><li>Lowongan banyak, tapi yang keterima dikit</li><li>Persaingan yang brutal (<strong>100+ resume untuk 1 role pekerjaan it’s a damn survival game</strong>)</li><li>Seringkali bukan yang paling jago yang lolos, tapi yang paling “fit”</li></ul><p>Dan di kondisi kaya gini, <strong>margin of error itu kecil banget.<br></strong>Satu kalimat bisa jadi pembeda antara:</p><blockquote>“Selamat, anda lolos ketahap berikutnya”</blockquote><p>atau</p><blockquote>“Terima kasih sudah melamar”</blockquote><h4>7 Pelajaran Brutal yang Gw Dapet</h4><p>Gw ngga mau ini cuma jadi cerita sedih belaka. ini hikmah yang gw dapet:<br><strong>1. First Impression Itu Nggak Adil — Tapi Nyata; </strong>Boleh ngga suka, tapi gini sistemnya.</p><p><strong>2. Kejujuran Perlu “Dikemas”; </strong>Jujur itu penting. Tapi cara penyampaiannya jauh lebih penting.</p><p><strong>3. Jangan Jawab Lebih Dari yang Ditanya<br></strong>Kadang kita over-explain… dan malah jadi bumerang buat kita.</p><p><strong>4. Persepsi &gt; Niat<br></strong>Kita bisa punya niat terbaik. Tapi yang dinilai adalah persepsi mereka.</p><p><strong>5. Positioning Diri Itu Krusial<br></strong>Kita bukan cuman kandidat. Kita itu “produk” yang lagi dipresentasikan.</p><p><strong>6. Setiap Kata di Interview Ada Konsekuensinya<br></strong>Ini bukan sekedar berbincang. Ini negosiasi masa depan.</p><p><strong>7. Gagal Itu Data, Bukan Akhir Dari Segalanya<br></strong>Kalau gw legowo dan belajar dari sini, ini bukan kegagalan melainkan investasi.</p><h4>Jadi sekarang gimana?</h4><p>Gw bisa aja terus nyalahin diri sendiri.<br>Atau…<br>Gw terima kenyataan kalau:</p><blockquote>Nasi Udah Jadi Bubur.</blockquote><p>Tapi bubur itu masih bisa dikasih:<br> — Ayam<br> — Kerupuk<br> — Sambel<br>Alias masih bisa dibuat “lebih enak”.</p><h4>Kalau lo lagi di posisi yang sama</h4><blockquote>Ngerasa Gagal…<br>Nyesel Sama Diri Sendiri…<br>Looping kejadian “harusnya gw ga ngomong gitu”</blockquote><p>Dengerin ini:</p><blockquote>Lu bukan gagal karena lu bodoh.<br>Lu cuma lagi belajar cara main di dunia yang keras &amp; kejam ini.</blockquote><blockquote><strong>“</strong>Boleh jadi kamu membenci sesuatu, padahal ia amat baik bagimu, dan boleh jadi (pula) kamu menyukai sesuatu, padahal ia amat buruk bagimu.<strong>” </strong><em>(QS. Al-Baqarah: 216)</em></blockquote><p>Dan mungkin… ini bukan akhir dari cerita gw.<br><strong>Tapi cara Tuhan ngarahin gw ke tempat yang lebih tepat.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29f99aa183a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bagaimana Cara ku menjadi Developer Handal bersama Codepolitan dan Alibaba Cloud]]></title>
            <link>https://naufaltechhub.medium.com/bagaimana-cara-ku-menjadi-developer-handal-bersama-codepolitan-dan-alibaba-cloud-d8cde1cbcf43?source=rss-1ea0ae4711e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8cde1cbcf43</guid>
            <category><![CDATA[alibabacloud]]></category>
            <category><![CDATA[codepolitan]]></category>
            <category><![CDATA[devhandal]]></category>
            <dc:creator><![CDATA[Muhammad Naufal Hanif]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 04:19:20 GMT</pubDate>
            <atom:updated>2024-02-23T04:23:07.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Txz4XAR63a03QciPre6YKw.jpeg" /><figcaption><a href="https://www.devhandal.id/">https://www.devhandal.id/</a></figcaption></figure><p>Di era digital ini, peran developer semakin penting dalam membangun berbagai aplikasi dan website yang menunjang kehidupan sehari-hari. Menjadi developer handal dengan keahlian yang mumpuni pun menjadi dambaan banyak orang.</p><p>Perjalanan saya menjadi developer handal tidak lepas dari peran tiga platform edukasi ternama, yaitu <a href="https://www.devhandal.id/"><strong>DevHandal</strong></a>, <a href="https://www.codepolitan.com/"><strong>Codepolitan</strong></a> dan <a href="https://www.alibabacloud.com/"><strong>Alibaba Cloud</strong></a>. Ketiga platform ini menyediakan berbagai program pembelajaran dan pelatihan yang membantu saya meningkatkan kemampuan coding dan memahami berbagai teknologi terbaru.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CN9WXY6KYmMZt19jvV-8-Q.jpeg" /><figcaption><a href="https://www.codepolitan.com/">https://www.codepolitan.com/</a></figcaption></figure><p><strong>Memulai langkah pertama dengan Codepolitan</strong></p><p>Awal mula ketertarikan saya pada dunia coding muncul saat saya masih duduk di bangku SMA. Saat itu, saya mengikuti kelas online di <strong>Codepolitan</strong> untuk mempelajari bahasa pemrograman dasar seperti HTML, CSS, dan JavaScript. Materi yang disampaikan mudah dipahami dan aplikatif, sehingga saya semakin termotivasi untuk mendalami ilmu coding.</p><p><strong>Mengembangkan keahlian dengan program DevHandal</strong></p><p>Seiring dengan perkembangan teknologi, saya ingin terus meningkatkan keahlian coding dan mempelajari teknologi baru. Pada tahun 2023, saya berkesempatan mengikuti program <strong>DevHandal</strong> yang diselenggarakan oleh <strong>Codepolitan</strong> dan <strong>Alibaba Cloud</strong>. Program ini memberikan beasiswa akses gratis ke kelas JavaScript expert selama satu tahun.</p><p><strong>Manfaat mengikuti program DevHandal:</strong></p><ul><li><strong>Materi pembelajaran yang komprehensif:</strong> Program DevHandal menyediakan materi pembelajaran yang komprehensif dan up-to-date, mulai dari dasar-dasar JavaScript hingga pengembangan aplikasi web modern dengan framework populer seperti ReactJS dan VueJS.</li><li><strong>Mentor berpengalaman:</strong> Saya berkesempatan belajar dari mentor-mentor berpengalaman di industri teknologi yang selalu siap membantu dan memberikan solusi atas permasalahan yang saya hadapi selama proses belajar.</li><li><strong>Komunitas developer yang aktif:</strong> Program DevHandal memiliki komunitas developer yang aktif dan suportif. Saya dapat bertukar informasi, berdiskusi, dan saling membantu dengan para developer lainnya.</li><li><strong>Sertifikasi internasional:</strong> Setelah menyelesaikan program DevHandal, saya mendapatkan sertifikasi internasional dari <strong>Alibaba Cloud</strong> yang diakui secara global. Sertifikasi ini menjadi bukti kompetensi dan meningkatkan nilai jual saya di pasar kerja.</li></ul><p><strong>Dampak positif mengikuti program DevHandal:</strong></p><ul><li><strong>Peningkatan kemampuan coding:</strong> Kemampuan coding saya meningkat pesat setelah mengikuti program DevHandal. Saya dapat memahami berbagai konsep pemrograman dengan lebih baik dan mampu mengembangkan aplikasi web yang kompleks.</li><li><strong>Pengembangan soft skills:</strong> Selain kemampuan coding, program DevHandal juga membantu saya mengembangkan soft skills seperti problem solving, critical thinking, dan communication skills.</li><li><strong>Peluang kerja yang lebih luas:</strong> Dengan keahlian dan sertifikasi yang saya dapatkan, saya memiliki peluang kerja yang lebih luas di berbagai perusahaan teknologi.</li></ul><p><strong>Tips menjadi developer handal:</strong></p><ul><li><strong>Tetap semangat belajar:</strong> Dunia teknologi selalu berkembang pesat, sehingga penting untuk selalu belajar dan mengikuti perkembangan teknologi terbaru.</li><li><strong>Berlatih secara konsisten:</strong> Semakin sering berlatih, semakin mahir kemampuan coding Anda.</li><li><strong>Bergabung dengan komunitas developer:</strong> Bergabung dengan komunitas developer dapat membantu Anda bertukar informasi, berdiskusi, dan saling membantu dengan para developer lainnya.</li><li><strong>Jangan mudah menyerah:</strong> Menjadi developer handal membutuhkan waktu dan dedikasi. Jangan mudah menyerah ketika menghadapi kesulitan dan teruslah berusaha untuk mencapai tujuan Anda.</li></ul><p>Menjadi developer handal bukan hal yang mustahil. Dengan tekad, kerja keras, dan platform edukasi yang tepat, Anda dapat mencapai tujuan Anda. Saya bersyukur atas kesempatan yang diberikan untuk mengikuti program DevHandal dan mendapatkan manfaat yang luar biasa. Saya yakin, program ini dapat membantu Anda menjadi developer handal yang siap bersaing di dunia industri teknologi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8cde1cbcf43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Web Scraping With Selenium: Store Deals Data Extraction]]></title>
            <link>https://naufaltechhub.medium.com/advanced-web-scraping-with-selenium-store-deals-data-extraction-e08026bb6f3c?source=rss-1ea0ae4711e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e08026bb6f3c</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-scraping]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[selenium]]></category>
            <dc:creator><![CDATA[Muhammad Naufal Hanif]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 04:16:52 GMT</pubDate>
            <atom:updated>2024-02-01T04:26:04.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*kLm2yzHrcitmvUqIj5s9xQ.jpeg" /></figure><p>Continuing our<a href="https://medium.com/@codewithnaufal/advanced-web-scraping-with-selenium-extracting-and-organizing-upcoming-sales-data-32ea208d5a09"> Advanced Web Scraping With Selenium</a> series, in this article, we will improve our scraping skills again!</p><p><a href="https://www.rakuten.com/stores/all">Rakuten</a> is a popular online marketplace, that offers a vast array of products and deals from various stores. Our goal is to use Selenium to scrape store deals data and handle infinite scrolling pages.</p><p>The data we’ll extract are:</p><ul><li><strong>store names</strong></li><li><strong>images</strong></li><li><strong>descriptions</strong></li><li>timestamps (python side)</li></ul><p><strong>Step 1: As always, first of all, go ahead to the </strong><a href="https://www.rakuten.com/stores/all"><strong>Rakuten</strong></a><strong> Website, we will analyze the website.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9FIys3GgxzebvAo4Fc_4bA.png" /></figure><p>There are several to note here, as we can see from the beginning of the page load, the items are not simultaneously loaded, we have to scroll down to load the other items. we can notify by seeing the height length of the scroller from the top to the bottom. So, later we will handle this thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqC2mEDi7PMFVMFAx4J_dg.png" /></figure><ul><li><strong>Container Xpath:</strong> //*[<a href="http://twitter.com/id">@id</a>=”main-content”]/div[4]/div[9]/div/div/div[2]/div[1]</li><li><strong>Main Content Xpath:</strong> //*[<a href="http://twitter.com/id">@id</a>=”main-content”]</li><li><strong>Store Name Selector:</strong> a div:nth-child(2) div:nth-child(1)</li><li><strong>Image URL Selector:</strong> a div:nth-child(1) img</li><li><strong>Description Selector:</strong> a div:nth-child(2) div:nth-child(2) div:nth-child(2) span:nth-child(1)</li></ul><p>nth:child(1) is just a method to get an element on a certain index, nth:child uses 1 based index. For instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7AnAnRTzAEjbVDEUJ1887Q.png" /></figure><p><strong>Selector Stack:</strong> a div:nth-child(2) div:nth-child(2) div:nth-child(2) span:nth-child(1)</p><p><strong>Step 2: Import necessary libraries and define the chrome option configuration.</strong></p><pre>import datetime<br>import time<br>import pandas as pd<br>from selenium import webdriver<br>from selenium.common.exceptions import NoSuchElementException<br>from selenium.webdriver.common.by import By<br>from selenium.webdriver.common.action_chains import ActionChains<br>from selenium.webdriver.common.actions.wheel_input import ScrollOrigin<br>from selenium.webdriver.support.ui import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br><br><br>def configure_chrome_options():<br>    options = webdriver.ChromeOptions()<br>    options.add_experimental_option(&quot;excludeSwitches&quot;, [&quot;enable-automation&quot;])<br>    options.add_experimental_option(&#39;useAutomationExtension&#39;, False)<br>    options.add_experimental_option(&#39;detach&#39;, True)<br>    options.add_argument(&#39;--disable-blink-features=AutomationControlled&#39;)<br>    options.add_argument(&quot;--disable-extensions&quot;)<br>    options.add_argument(&#39;--no-sandbox&#39;)<br>    options.add_argument(&#39;--disable-infobars&#39;)<br>    options.add_argument(&#39;--disable-dev-shm-usage&#39;)<br>    options.add_argument(&#39;--disable-browser-side-navigation&#39;)<br>    options.add_argument(&#39;--disable-gpu&#39;)<br>    options.add_argument(&#39;--blink-settings=imagesEnabled=false&#39;)<br>    options.add_argument(<br>        &#39;user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36&#39;<br>    )<br>    return options</pre><p><strong>Step 3: Define driver initialization.</strong></p><pre>def initialize_driver(options):<br>    driver = webdriver.Chrome(options=options)<br>    driver.maximize_window()<br>    return driver</pre><p><strong>Step 4: Define scrape data function.</strong></p><pre>def scrape_data(driver, container):<br>    store_name_selector = &#39;a div:nth-child(2) div:nth-child(1)&#39;<br>    image_url_selector = &#39;a div:nth-child(1) img&#39;<br>    description_selector = &#39;a div:nth-child(2) div:nth-child(2) span:nth-child(1)&#39;<br><br>    data = []<br>    last_element = None<br><br>    while True:<br>        try:<br>            items = container.find_elements(By.CSS_SELECTOR, &#39;div.css-0&#39;)<br>            if last_element:<br>                items = items[items.index(last_element) + 1:]<br><br>            for item in items:<br>                store_name = item.find_element(By.CSS_SELECTOR, store_name_selector).text<br>                image_url = item.find_element(By.CSS_SELECTOR, image_url_selector).get_attribute(&#39;src&#39;)<br>                description = item.find_element(By.CSS_SELECTOR, description_selector).text<br><br>                deals = {<br>                    &#39;Store Name&#39;: store_name,<br>                    &#39;Image URL&#39;: image_url,<br>                    &#39;Description&#39;: description,<br>                    &#39;Timestamp&#39;: datetime.datetime.now().strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>                }<br><br>                print(deals)<br>                data.append(deals)<br><br>            current_last_element = items[-1]<br>            print(f&#39;Total Scraped: {len(data)}&#39;)<br>            last_element = current_last_element<br>            print(&#39;Scrolling to last element..&#39;)<br>            driver.execute_script(&quot;arguments[0].scrollIntoView(true);&quot;, last_element)<br>            time.sleep(1.5)<br><br>        except (NoSuchElementException, IndexError, Exception) as e:<br>            print(e)<br>            break<br><br>    return data</pre><p>last_element is a common technique for handling duplicated elements and ensuring that we don&#39;t scrape the same data multiple times during consecutive iterations. Let&#39;s break down how it works:</p><pre>last_element = None</pre><p>Initially, last_element is set to None, indicating that there is no previous element.</p><pre>if last_element:<br>    items = items[items.index(last_element) + 1:]</pre><p>This condition checks if last_element exists (i.e., it&#39;s not None). If it exists, it means that there was a previous iteration, and we want to avoid scraping the same data again. So, it adjusts the items list to start from the next element after last_element.</p><pre>current_last_element = items[-1]<br>last_element = current_last_element</pre><p>After processing the current set of items, the last element of the current iteration (current_last_element) is stored in last_element. This becomes the reference point for the next iteration.</p><p>This approach ensures that you only scrape new data in each iteration, preventing redundancy and duplication. By keeping track of the last element processed, you can efficiently handle scenarios where elements might be repeated due to dynamic loading or paginated content.</p><p><strong>Step 5: Define the main function.</strong></p><pre>def main():<br>    url = &#39;https://www.rakuten.com/stores/all&#39;<br>    container_xpath = &#39;//*[@id=&quot;main-content&quot;]/div[4]/div[9]/div/div/div[2]/div[1]&#39;<br>    main_content_xpath = &#39;//*[@id=&quot;main-content&quot;]&#39;<br>    csv_path = &#39;rakuten.csv&#39;<br><br>    options = configure_chrome_options()<br>    driver = initialize_driver(options)<br><br>    try:<br>        driver.get(url)<br>        WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, main_content_xpath)))<br>        scroll_element = driver.find_element(By.XPATH, main_content_xpath)<br>        scroll_from_element = ScrollOrigin.from_element(scroll_element)<br><br>        ActionChains(driver).scroll_from_origin(scroll_from_element, 0, 3000).perform()<br>        WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, container_xpath)))<br><br>        container = driver.find_element(By.XPATH, container_xpath)<br>        driver.execute_script(&quot;arguments[0].scrollIntoView(true);&quot;, container)<br><br>        data = scrape_data(driver, container)<br>        df = pd.DataFrame(data)<br>        df.to_csv(csv_path, index=False)<br>    finally:<br>        driver.quit()<br><br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>Let’s break down the scenario:</p><p><strong>Navigating to the Rakuten Website and Setting Up Scrolling:</strong></p><pre>driver.get(url)<br>WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, main_content_xpath)))<br>scroll_element = driver.find_element(By.XPATH, main_content_xpath)<br>scroll_from_element = ScrollOrigin.from_element(scroll_element)</pre><ul><li>Navigating to the provided URL using driver.get(url).</li><li>Wait for the main content area to be visible using WebDriverWait.</li><li>The main content element is located and used for scrolling.</li></ul><p><strong>Performing Scrolling and Waiting for Container Visibility:</strong></p><pre>ActionChains(driver).scroll_from_origin(scroll_from_element, 0, 3000).perform()<br>WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, container_xpath)))</pre><ul><li>Using ActionChains, it scrolls from the main content element to simulate loading more content.</li><li>It then waits for the container element (the holder of store information) to become visible.</li></ul><p><strong>Locating Container Element and Scrolling to It:</strong></p><pre>container = driver.find_element(By.XPATH, container_xpath)<br>driver.execute_script(&quot;arguments[0].scrollIntoView(true);&quot;, container)</pre><ul><li>Locating the container.</li><li>The scroll_to_element function is called to ensure the container is fully visible.</li></ul><p><strong>Scraping Data, Creating DataFrame, and Saving to CSV:</strong></p><pre>data = scrape_data(driver, container)<br>df = pd.DataFrame(data)<br>df.to_csv(csv_path, index=False)</pre><ul><li>The scrape_data function is called with the WebDriver and container as arguments to extract store name information.</li><li>The extracted data is converted into a pandas DataFrame (df).</li><li>The DataFrame is saved to a CSV file (csv_path -&gt; rakuten.csv).</li></ul><p><strong>Quit driver within </strong><strong>finally Block:</strong></p><pre>finally:<br>    driver.quit()</pre><p>The Full Code:</p><pre>import datetime<br>import time<br>import pandas as pd<br>from selenium import webdriver<br>from selenium.common.exceptions import NoSuchElementException<br>from selenium.webdriver.common.by import By<br>from selenium.webdriver.common.action_chains import ActionChains<br>from selenium.webdriver.common.actions.wheel_input import ScrollOrigin<br>from selenium.webdriver.support.ui import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br><br><br>def configure_chrome_options():<br>    options = webdriver.ChromeOptions()<br>    options.add_experimental_option(&quot;excludeSwitches&quot;, [&quot;enable-automation&quot;])<br>    options.add_experimental_option(&#39;useAutomationExtension&#39;, False)<br>    options.add_experimental_option(&#39;detach&#39;, True)<br>    options.add_argument(&#39;--disable-blink-features=AutomationControlled&#39;)<br>    options.add_argument(&quot;--disable-extensions&quot;)<br>    options.add_argument(&#39;--no-sandbox&#39;)<br>    options.add_argument(&#39;--disable-infobars&#39;)<br>    options.add_argument(&#39;--disable-dev-shm-usage&#39;)<br>    options.add_argument(&#39;--disable-browser-side-navigation&#39;)<br>    options.add_argument(&#39;--disable-gpu&#39;)<br>    options.add_argument(&#39;--blink-settings=imagesEnabled=false&#39;)<br>    options.add_argument(<br>        &#39;user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36&#39;<br>    )<br>    return options<br><br><br>def initialize_driver(options):<br>    driver = webdriver.Chrome(options=options)<br>    driver.maximize_window()<br>    return driver<br><br><br>def scrape_data(driver, container):<br>    store_name_selector = &#39;a div:nth-child(2) div:nth-child(1)&#39;<br>    image_url_selector = &#39;a div:nth-child(1) img&#39;<br>    description_selector = &#39;a div:nth-child(2) div:nth-child(2) div:nth-child(2) span:nth-child(1)&#39;<br><br>    data = []<br>    last_element = None<br><br>    while True:<br>        try:<br>            items = container.find_elements(By.CSS_SELECTOR, &#39;div.css-0&#39;)<br>            if last_element:<br>                items = items[items.index(last_element) + 1:]<br><br>            for item in items:<br>                store_name = item.find_element(By.CSS_SELECTOR, store_name_selector).text<br>                image_url = item.find_element(By.CSS_SELECTOR, image_url_selector).get_attribute(&#39;src&#39;)<br>                description = item.find_element(By.CSS_SELECTOR, description_selector).text<br><br>                deals = {<br>                    &#39;Store Name&#39;: store_name,<br>                    &#39;Image URL&#39;: image_url,<br>                    &#39;Description&#39;: description,<br>                    &#39;Timestamp&#39;: datetime.datetime.now().strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>                }<br><br>                print(deals)<br>                data.append(deals)<br><br>            current_last_element = items[-1]<br>            print(f&#39;Total Scraped: {len(data)}&#39;)<br>            last_element = current_last_element<br>            print(&#39;Scrolling to last element..&#39;)<br>            driver.execute_script(&quot;arguments[0].scrollIntoView(true);&quot;, last_element)<br>            time.sleep(1.5)<br><br>        except (NoSuchElementException, IndexError, Exception) as e:<br>            print(e)<br>            break<br><br>    return data<br><br><br>def main():<br>    url = &#39;https://www.rakuten.com/stores/all&#39;<br>    container_xpath = &#39;//*[@id=&quot;main-content&quot;]/div[4]/div[9]/div/div/div[2]/div[1]&#39;<br>    main_content_xpath = &#39;//*[@id=&quot;main-content&quot;]&#39;<br>    csv_path = &#39;rakuten.csv&#39;<br><br>    options = configure_chrome_options()<br>    driver = initialize_driver(options)<br><br>    try:<br>        driver.get(url)<br>        WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, main_content_xpath)))<br>        scroll_element = driver.find_element(By.XPATH, main_content_xpath)<br>        scroll_from_element = ScrollOrigin.from_element(scroll_element)<br><br>        ActionChains(driver).scroll_from_origin(scroll_from_element, 0, 3000).perform()<br>        WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, container_xpath)))<br><br>        container = driver.find_element(By.XPATH, container_xpath)<br>        driver.execute_script(&quot;arguments[0].scrollIntoView(true);&quot;, container)<br><br>        data = scrape_data(driver, container)<br>        df = pd.DataFrame(data)<br>        df.to_csv(csv_path, index=False)<br>    finally:<br>        driver.quit()<br><br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>In this journey through advanced web scraping, we’ve explored the potent capabilities of Selenium for data extraction. The code presented provides a robust foundation, showcasing the strategic use of Chrome options, WebDriver initialization, and intelligent scrolling.</p><p>The incorporation of last_element demonstrates a smart approach to handling duplicate elements, ensuring efficient and precise data extraction. Adapt and apply this knowledge to your projects!</p><p>Happy scraping!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e08026bb6f3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Web Scraping with Selenium: Extracting and Organizing Upcoming Sales Data]]></title>
            <link>https://naufaltechhub.medium.com/advanced-web-scraping-with-selenium-extracting-and-organizing-upcoming-sales-data-32ea208d5a09?source=rss-1ea0ae4711e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/32ea208d5a09</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-extraction]]></category>
            <dc:creator><![CDATA[Muhammad Naufal Hanif]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 07:52:01 GMT</pubDate>
            <atom:updated>2024-01-22T08:01:09.563Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkVnUZ__AIgJSkRNjPkQWA.jpeg" /></figure><p>What’s up folks! In this article, we embark on a journey to elevate your web scraping prowess by extracting upcoming sales information using Selenium and Python, as well as organizing it with Pandas. Following our previous adventure in A Beginner’s Guide to Web Scraping with Selenium, where we delved into eBay product extraction, we now set our sights on the realm of upcoming sales.</p><p>Without further ado, let’s get started!</p><p><strong>Modules Requirements:</strong></p><ul><li>Selenium</li><li>Pandas</li></ul><p><strong>Section 1: Analyze The Website</strong></p><p>Target: <a href="https://tjsc.com/Sales/UpcomingSales">The Judicial Sales Corporation</a></p><p>Scraping Challenges:</p><ul><li>We will get only all <strong>‘Cook’</strong> County.</li><li>We will create 2 Spreadsheets: <strong>Sorted by auction date</strong> and <strong>Sorted by zip code</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71tdOO8T3UjN5LCSPC__Ww.png" /></figure><p><strong>Data to Extract:</strong><br>- Sale Date<br>- Sale Time<br>- File Number<br>- Case Number<br>- Firm Name<br>- Address<br>- City<br>- Zip Code<br>- Opening Bid<br>- Required % Down<br>- Sale Amount<br>- Continuance<br>- Sold To</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ixsjN-5NB-ds03Um0WioJQ.png" /></figure><p><strong>One of the keys </strong>to mastering handling pagination is to analyze the next and previous buttons of the page. A <strong>disabled ‘Previous’ button</strong> indicates you’re on the <strong>first page</strong>. Conversely, a <strong>disabled ‘Next’ button</strong> means you’ve reached the <strong>last page</strong>. Analyzing these states can help you easily optimize your navigation logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cAHlBjo-bevjFC64QNO6g.png" /></figure><p><strong>Locators:</strong></p><ul><li><strong>Table Xpath:</strong> //*[<a href="http://twitter.com/id">@id</a>=”basic-datatables”]</li><li><strong>Next Button Xpath: </strong>//*[<a href="http://twitter.com/id">@id</a>=”basic-datatables_paginate”]/ul/li[7]/a</li><li><strong>Next Button Selector at the end of the page:</strong> li.next.disabled</li></ul><p>If we take a look at this image, we can see that the <strong>class name of the next button</strong> at the end of the page has <strong>changed from ‘next’ to ‘next disabled’</strong> which means, we can just use this approach as our end page checker later.</p><p><strong>What is XPath?</strong></p><p>XPath (XML Path Language) is a locator strategy used to navigate through elements in HTML or XML documents. On our XPath, the expression //*[@id=&quot;basic-datatables_paginate&quot;]/ul/li[7]/a means it’s selecting any element (*) in the document with an attribute id equal to &quot;basic-datatables_paginate,&quot; then navigate to its ul child, followed by the 7th li child, and finally select the a (anchor) element.</p><p><strong>Section 2: Import necessary libraries and define configurations</strong></p><pre>import pandas as pd<br>from selenium import webdriver<br>from selenium.webdriver.common.by import By<br>from selenium.webdriver.support.ui import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br>from selenium.common.exceptions import NoSuchElementException, TimeoutException<br>import logging<br><br># Configuration<br>URL = &#39;https://tjsc.com/Sales/UpcomingSales&#39;<br>TABLE_XPATH = &#39;//*[@id=&quot;basic-datatables&quot;]&#39;<br>NEXT_PAGE_XPATH = &#39;//*[@id=&quot;basic-datatables_paginate&quot;]/ul/li[7]/a&#39;<br>DISABLED_NEXT_BUTTON_SELECTOR = &#39;li.next.disabled&#39;<br># Configure logging to run on INFO Level<br>logging.basicConfig(level=logging.INFO)</pre><p>We will use logging modules to log all our scraping activities.</p><p><strong>Why would we use logging instead of regular print?</strong></p><ul><li><strong>Control Levels</strong>: Logging has different levels (DEBUG, INFO, WARNING, ERROR, CRITICAL) for controlling output verbosity.</li><li><strong>Flexibility</strong>: Logging allows redirecting logs to files, consoles, or external services.</li><li><strong>Timestamps</strong>: Logs automatically include timestamps for tracking events</li><li><strong>Severity Levels</strong>: Log levels categorize the severity of messages.</li><li><strong>Structured Output</strong>: Logging supports structured log output for easier analysis.</li><li><strong>Error Handling</strong>: Provides a standardized way to report errors with stack traces.</li><li><strong>Consistency</strong>: Ensures consistent formatting of log messages.</li><li><strong>Integration</strong>: Integrates well with libraries and frameworks using the Python logging module.</li></ul><p><strong>Section 3: Set up WebDriver and any requirements variables</strong></p><pre>def main():<br>    # Set up Chrome WebDriver options<br>    options = webdriver.ChromeOptions()<br>    # Disables &quot;Chrome is being controlled by automated test software&quot; message<br>    options.add_experimental_option(&quot;excludeSwitches&quot;, [&quot;enable-automation&quot;])<br>    options.add_experimental_option(&#39;useAutomationExtension&#39;, False)<br>    options.add_argument(&#39;--disable-blink-features=AutomationControlled&#39;)<br><br>    options.add_argument(&quot;--disable-extensions&quot;)  # Disables extensions<br>    options.add_argument(&#39;--no-sandbox&#39;)  # Bypass OS security model<br>    options.add_argument(&#39;--disable-infobars&#39;)  # Disables infobars<br>    options.add_argument(&#39;--disable-dev-shm-usage&#39;)  # overcome limited resource problems<br>    options.add_argument(&#39;--disable-browser-side-navigation&#39;)  # Disables browser side navigation<br>    options.add_argument(&#39;--disable-gpu&#39;)  # Disables GPU hardware acceleration<br>    options.add_argument(&#39;--blink-settings=imagesEnabled=false&#39;)  # Disables images<br>    options.add_argument(&#39;--headless&#39;)  # Runs in headless mode<br>    options.add_argument(<br>        &#39;user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36&#39;<br>    )  # Sets user agent to mimic a real browser<br><br>    # Initialize Chrome WebDriver<br>    driver = webdriver.Chrome(options=options)<br>    driver.maximize_window()<br>    driver.get(URL)<br><br>    # Initialize counter and data variables<br>    counter = 1<br>    data = []</pre><ul><li>Counter: used to count pages.</li><li>data = used to accommodate our upcoming sales data.</li></ul><p><strong>Section 4: Extract data and handle pagination.</strong></p><p>Since we will handle a dynamic pagination, we will use a while loop.</p><p><strong>main():</strong></p><pre>def main():<br>    ...<br>    while True:<br>        try:<br>            # Log page scraping progress<br>            logging.info(f&#39;Scraping page {counter}..&#39;)<br><br>            # Wait for the table to be visible<br>            WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, TABLE_XPATH)))<br>            table = driver.find_element(By.XPATH, TABLE_XPATH)<br><br>            # Scrape data from the current page<br>            scrape_data(table, data)<br><br>            # Check for end of pagination<br>            end_of_page = handle_pagination(driver, counter, data)<br>            if end_of_page:<br>                break<br><br>            # Increment page counter<br>            counter += 1<br><br>        except (NoSuchElementException, TimeoutException) as e:<br>            # Handle errors and exit the script<br>            logging.error(f&quot;An error occurred: {e}&quot;)<br>            driver.quit()<br>            break<br>    ...<br><br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><ul><li>NoSuchElementException: used to catch an error if there’s an not found element.</li><li>TimeoutException: used to catch an error if there’s an EC (expected conditions) that’s not fulfilled.</li></ul><p><strong>scrape_data(table, data):</strong></p><pre>def scrape_data(table, data):<br>    # Take only the &#39;Cook&#39; county data<br>    table_rows = [<br>        row for row in table.find_elements(By.XPATH, f&quot;{TABLE_XPATH}/tbody/tr&quot;)<br>        if row.find_element(By.XPATH, &#39;./td[8]&#39;).text == &#39;Cook&#39;<br>    ]<br>    for table_data in table_rows:<br>        td = [td.text for td in table_data.find_elements(By.XPATH, &#39;./td[position() &lt;= 14]&#39;)]<br>        data.append({<br>            &quot;Sale Date&quot;: td[0],<br>            &quot;Sale Time&quot;: td[1],<br>            &quot;File Number&quot;: td[2],<br>            &quot;Case Number&quot;: td[3],<br>            &quot;Firm Name&quot;: td[4],<br>            &quot;Address&quot;: td[5],<br>            &quot;City&quot;: td[6],<br>            &quot;County&quot;: td[7],<br>            &quot;Zip Code&quot;: td[8],<br>            &quot;Opening Bid&quot;: td[9],<br>            &quot;Required % Down&quot;: td[10],<br>            &quot;Sale Amount&quot;: td[11],<br>            &quot;Continuance&quot;: td[12],<br>            &quot;Sold To&quot;: td[13]<br>        })<br><br>def main():<br>    ...</pre><p>The scrape_data function is designed to extract information from the table, specifically focusing on rows where the value in the 8th column (td[8]) is equal to &#39;Cook&#39;. This ensures that only data related to the &#39;Cook&#39; county is considered.</p><p>Here’s a breakdown of the function:</p><ul><li>It iterates through each row in the table using a list comprehension.</li><li>For each row, it checks if the text in the 8th column (./td[8]) is equal to &#39;Cook&#39; (is the county column equal to ‘Cook’?).</li><li>If the condition is satisfied, it extracts text from the first 14 columns of that row (td.text for td in table_data.find_elements(By.XPATH, &#39;./td[position() &lt;= 14]&#39;)) means extracting all the column&#39;s values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFLbAHXOWI1HimEEWymSGg.png" /></figure><ul><li>The extracted data is then appended to the data list as a dictionary, with keys representing different columns such as &#39;Sale Date&#39;, &#39;Sale Time&#39;, etc.</li></ul><p><strong>handle_pagination(driver, counter, data):</strong></p><pre>def handle_pagination(driver, counter, data):<br>    try:<br>        # return true if disabled next button found<br>        driver.find_element(By.CSS_SELECTOR, DISABLED_NEXT_BUTTON_SELECTOR)<br>        return True<br>    except Exception:<br>        # if it&#39;s not, find the next page button,scroll to it and click it<br>        next_page = driver.find_element(By.XPATH, NEXT_PAGE_XPATH)<br>        driver.execute_script(&#39;arguments[0].scrollIntoView(true)&#39;, next_page)<br>        next_page.click()<br>        # log the current page and total scraped data<br>        logging.info(f&#39;Page {counter} scraped. Total: {len(data)}&#39;)<br>        return False<br><br><br>def main():<br>    ...</pre><p>The handle_pagination function manages the navigation through paginated pages on a website.</p><ul><li>If the ‘Next’ button is disabled (indicating the last page), the function returns True.</li><li>If an exception occurs (indicating the ‘Next’ button is not disabled), it proceeds to locate and click the ‘Next’ button using an XPath (NEXT_PAGE_XPATH).</li><li>After clicking, it logs the progress and returns False to indicate there are more pages to scrape.</li></ul><p><strong>Section 5: Organize data and export to Excel.</strong></p><pre>def main():<br>    ...<br>    # Create DataFrames and sort by relevant columns<br>    df_sheet1 = pd.DataFrame(data).sort_values(by=&#39;Sale Date&#39;)<br>    df_sheet2 = pd.DataFrame(data).sort_values(by=&#39;Zip Code&#39;)<br><br>    # Export to Excel file with two sheets<br>    with pd.ExcelWriter(&#39;upcoming_sales.xlsx&#39;, engine=&#39;xlsxwriter&#39;) as writer:<br>        df_sheet1.to_excel(writer, sheet_name=&#39;By Auction Date&#39;, index=False)<br>        df_sheet2.to_excel(writer, sheet_name=&#39;By Zip Code&#39;, index=False)<br><br>    # Log successful completion<br>    logging.info(&quot;Excel file with two sheets created: upcoming_sales.xlsx&quot;)</pre><ul><li>df_sheet1 and df_sheet2 are two Pandas DataFrames created from the collected data.</li><li>pd.DataFrame(data) converts the collected data (list of dictionary) into a DataFrame.</li><li>sort_values(by=&#39;&#39;) sorts DataFrame based on the inputted column (By Sale Date and By Zip Code).</li><li>pd.ExcelWriter is used to create an Excel file named &#39;upcoming_sales.xlsx&#39;.</li><li>df_sheet1 is written to the &#39;By Auction Date&#39; sheet, and df_sheet2 is written to the &#39;By Zip Code&#39; sheet.</li></ul><p>The Complete Code:</p><pre>import pandas as pd<br>from selenium import webdriver<br>from selenium.webdriver.common.by import By<br>from selenium.webdriver.support.ui import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br>from selenium.common.exceptions import NoSuchElementException, TimeoutException<br>import logging<br><br><br>URL = &#39;https://tjsc.com/Sales/UpcomingSales&#39;<br>TABLE_XPATH = &#39;//*[@id=&quot;basic-datatables&quot;]&#39;<br>NEXT_PAGE_XPATH = &#39;//*[@id=&quot;basic-datatables_paginate&quot;]/ul/li[7]/a&#39;<br>DISABLED_NEXT_BUTTON_SELECTOR = &#39;li.next.disabled&#39;<br><br>logging.basicConfig(level=logging.INFO)<br><br><br><br>def scrape_data(table, data):<br>    table_rows = [<br>        row for row in table.find_elements(By.XPATH, f&quot;{TABLE_XPATH}/tbody/tr&quot;)<br>        if row.find_element(By.XPATH, &#39;./td[8]&#39;).text == &#39;Cook&#39;<br>    ]<br>    for table_data in table_rows:<br>        td = [td.text for td in table_data.find_elements(By.XPATH, &#39;./td[position() &lt;= 14]&#39;)]<br>        data.append({<br>            &quot;Sale Date&quot;: td[0],<br>            &quot;Sale Time&quot;: td[1],<br>            &quot;File Number&quot;: td[2],<br>            &quot;Case Number&quot;: td[3],<br>            &quot;Firm Name&quot;: td[4],<br>            &quot;Address&quot;: td[5],<br>            &quot;City&quot;: td[6],<br>            &quot;County&quot;: td[7],<br>            &quot;Zip Code&quot;: td[8],<br>            &quot;Opening Bid&quot;: td[9],<br>            &quot;Required % Down&quot;: td[10],<br>            &quot;Sale Amount&quot;: td[11],<br>            &quot;Continuance&quot;: td[12],<br>            &quot;Sold To&quot;: td[13]<br>        })<br><br><br>def handle_pagination(driver, counter, data):<br>    try:<br>        driver.find_element(By.CSS_SELECTOR, DISABLED_NEXT_BUTTON_SELECTOR)<br>        return True<br>    except Exception:<br>        next_page = driver.find_element(By.XPATH, NEXT_PAGE_XPATH)<br>        driver.execute_script(&#39;arguments[0].scrollIntoView(true)&#39;, next_page)<br>        next_page.click()<br>        logging.info(f&#39;Page {counter} scraped. Total: {len(data)}&#39;)<br>        return False<br><br><br>def main():<br>    options = webdriver.ChromeOptions()<br>    options.add_experimental_option(&quot;excludeSwitches&quot;, [&quot;enable-automation&quot;])<br>    options.add_experimental_option(&#39;useAutomationExtension&#39;, False)<br>    options.add_argument(&#39;--disable-blink-features=AutomationControlled&#39;)<br><br>    options.add_argument(&quot;--disable-extensions&quot;)<br>    options.add_argument(&#39;--no-sandbox&#39;)<br>    options.add_argument(&#39;--disable-infobars&#39;)<br>    options.add_argument(&#39;--disable-dev-shm-usage&#39;)<br>    options.add_argument(&#39;--disable-browser-side-navigation&#39;)<br>    options.add_argument(&#39;--disable-gpu&#39;)<br>    options.add_argument(&#39;--blink-settings=imagesEnabled=false&#39;)<br>    options.add_argument(&#39;--headless&#39;)<br>    options.add_argument(<br>        &#39;user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36&#39;<br>    )<br><br><br>    driver = webdriver.Chrome(options=options)<br>    driver.maximize_window()<br>    driver.get(URL)<br><br>    counter = 1<br>    data = []<br><br>    while True:<br>        try:<br>            logging.info(f&#39;Scraping page {counter}..&#39;)<br><br>            WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, TABLE_XPATH)))<br>            table = driver.find_element(By.XPATH, TABLE_XPATH)<br><br>            scrape_data(table, data)<br><br>            end_of_page = handle_pagination(driver, counter, data)<br>            if end_of_page:<br>                break<br><br>            counter += 1<br><br>        except (NoSuchElementException, TimeoutException) as e:<br>            logging.error(f&quot;An error occurred: {e}&quot;)<br>            driver.quit()<br>            break<br><br>    df_sheet1 = pd.DataFrame(data).sort_values(by=&#39;Sale Date&#39;)<br>    df_sheet2 = pd.DataFrame(data).sort_values(by=&#39;Zip Code&#39;)<br><br>    with pd.ExcelWriter(&#39;upcoming_sales.xlsx&#39;, engine=&#39;xlsxwriter&#39;) as writer:<br>        df_sheet1.to_excel(writer, sheet_name=&#39;By Auction Date&#39;, index=False)<br>        df_sheet2.to_excel(writer, sheet_name=&#39;By Zip Code&#39;, index=False)<br><br>    logging.info(&quot;Excel file with two sheets created: upcoming_sales.xlsx&quot;)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>This advanced web scraping showcased the power of Selenium and Python in efficiently extracting and organizing upcoming sales data. From data extraction and dynamic pagination handling to structured organization and export, each step was a testament to the capabilities of web scraping for data-driven insights.</p><p>Remember, web scraping is a powerful tool that requires responsible and ethical use. Always be mindful of the website’s terms of service and respect data privacy guidelines. Now armed with advanced web scraping skills, you’re ready to tackle diverse data extraction challenges in your scraping adventures. Happy scraping!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32ea208d5a09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Web Scraping with Selenium in Python: Extracting eBay Products]]></title>
            <link>https://naufaltechhub.medium.com/a-beginners-guide-to-web-scraping-with-selenium-in-python-extracting-ebay-products-5dfa29fc37a8?source=rss-1ea0ae4711e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dfa29fc37a8</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[data-scraping]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-mining]]></category>
            <dc:creator><![CDATA[Muhammad Naufal Hanif]]></dc:creator>
            <pubDate>Fri, 12 Jan 2024 23:37:13 GMT</pubDate>
            <atom:updated>2024-01-16T10:02:09.516Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JXncsYDJdvmWWcllg4811g.png" /></figure><p>Web scraping is a powerful technique that allows us to extract data from websites. In this article, we will walk you through the process of web scraping using Selenium in Python. Selenium is a popular tool for web automation and testing, but it can also be used effectively for web scraping. By the end of this guide, you will have a good understanding of how to use Selenium for web scraping and be able to extract data from websites on your own.</p><p><strong>Requirements:</strong><br>Before we get started, ensure you have the following:</p><ul><li>Latest PyCharm Community / Professional IDEA</li><li>Latest Chrome Browser installed</li></ul><p><strong>Why would we use Chrome instead of another?</strong></p><ul><li><strong>Dominating market share:</strong> Chrome dominates the web browser market, which translates to greater compatibility with websites and less frequent issues with dynamic content or rendering.</li><li><strong>Extensive extension library:</strong> Chrome offers a vast selection of extensions, including dedicated scraping tools, that can significantly enhance your scraping functionalities.</li><li><strong>Mature and active community:</strong> Chrome’s large user base and developer community lead to abundant documentation, tutorials, and troubleshooting resources.</li><li><strong>Has headless mode:</strong> Chrome’s headless mode runs efficiently without a GUI, ideal for server-side automation or scraping large datasets.</li></ul><p><strong>Step 1: Setting Up Project &amp; Installing Selenium:</strong></p><p>To begin, open your PyCharm IDEA, create a new project, choose Pure Python, and then create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*B_fmxrk2HZDKHsAZoZHprg.png" /></figure><p>Next, create a new Python file called app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNwE3CyR-GkheJj8bRY1Ew.png" /></figure><p>let’s install the necessary packages. Open your terminal (bottom left side) in PyCharm and enter the following command:</p><pre>pip install selenium</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*S3rUNiOSuM2DbzUoJ3hGEA.png" /></figure><p><strong>Step 2: Setting Up the Selenium Web Driver:</strong><br>Lucky for us, starting from Selenium version 4.14, we no longer have to install web driver things manually, because all of that stuff had been handled by Selenium Manager.</p><p>The web driver itself, it’s just like a remote control for your web browser. It allows you to control and automate every aspect of your browser interaction with a website, just like a human user would. This empowers you to perform various tasks, including:</p><ul><li><strong>Clicking on buttons and links</strong></li><li><strong>Filling out forms</strong></li><li><strong>Scrolling through pages</strong></li><li><strong>Extracting data from web elements</strong></li><li><strong>Running tests on web applications</strong></li></ul><p>Now, Before we going to set up the web driver, Let’s acquainted with Chrome options first.</p><p>Chrome Options is used to customize and configure the behaviour of the Chrome browser when launching it through ChromeDriver. Think of it as fine-tuning your Chrome experience for automation.</p><p>Here are some things Chrome Options can do:</p><ul><li><strong>Run Chrome in headless mode:</strong> This runs Chrome without the graphical user interface (GUI), making it useful for server-side automation or situations where you don’t need to see the browser window.</li><li><strong>Block image loading</strong>: We can temporarily disable images that show up from websites, which will help increase our Chrome speed.</li><li><strong>Setting up disk cache:</strong> We can also set up disk cache in Selenium to enhance performance and reduce network usage during our web scraping tasks.</li></ul><p>There are many configurations you can do with Chrome Options besides that, sadly, selenium documentation itself regarding this Chrome option is really poor, but don’t worry, because there are many communities there that will help you, such as <a href="http://stackoverflow.com/">stackoverflow.com</a>, <a href="http://selenium-python.readthedocs.io/">selenium-python.readthedocs.io</a> , and many more.</p><p>Okay, let’s just start our journey by setting up our web driver.</p><pre>from selenium import webdriver <br><br>if __name__ == &#39;__main__&#39;:<br>    chrome_options = webdriver.ChromeOptions() # Add options to chrome<br>    chrome_options.add_experimental_option(&#39;detach&#39;, True) # Keep the browser open<br>    chrome_options.add_argument(&#39;--disk-cache-size=0&#39;) # Disable cache<br>    chrome_options.add_argument(&#39;--blink-settings=imagesEnabled=false&#39;) # Disable image<br>    chrome_options.add_argument(&#39;--headless&#39;) # Enable headless mode<br>    driver = webdriver.Chrome(options=chrome_options)</pre><p>Next, set our target URL, we will target an e-commerce website which is eBay. We will gather information about new laptop products with 16 GB RAM that are available i.e.:</p><ul><li><strong>Product Link</strong></li><li><strong>Product Title</strong></li><li><strong>Product Price</strong></li><li><strong>Product Seller</strong></li><li><strong>Product Image URL</strong></li></ul><p>URL: https://www.ebay.com/sch/i.html?_from=R40&amp;_nkw=laptop&amp;_sacat=0&amp;LH_ItemCondition=1000&amp;RAM%2520Size=16%2520GB&amp;_dcat=177&amp;_ipg=240&amp;rt=nc&amp;LH_BIN=1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNdwQuuml4tNjc5QVk9L5g.png" /></figure><p>Inspect the page element by right-clicking the mouse on the page and choosing the inspect menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S3diQuJbojk2KxgOsoaMIg.png" /></figure><p>Find the container of the product list, by hovering on a certain element, it will colour the page automatically, representing what element we are pointing to. Here we have <strong>‘ul srp-results srp-list clearfix’ </strong>which is the element that holds all these products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpDI1oKjW7o2OCem5hA9-A.png" /></figure><p>Why would we have to find the container first? it’s important to make sure that we will just focus on the product lists, so whenever we find a specific element like this products selector <strong>‘div.s-item__wrapper clearfix’ </strong>it will only search within the products container scope</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nuKA5XKlWi-vCES0oHsVAw.png" /></figure><p>After we‘ve done with the products selector <strong>(‘div.s-item__wrapper clearfix’)</strong> , we have to find the information details to be extracted (title, price, etc). The easiest and fastest approach for retrieving our desired element is by directly inspecting the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPK-ELcsyDROH9oDUL4YyA.png" /></figure><p>These are all the remaining:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cuARlOj5dhIeN57TV2KlSA.png" /></figure><p>SELECTORS:</p><ul><li><strong>Container Selector:</strong> ul.srp-results.srp-list.clearfix</li><li><strong>Product Selector:</strong> div.s-item__wrapper.clearfix</li><li><strong>Link Selector:</strong> a.s-item__link</li><li><strong>Title Selector:</strong> div.s-item__title</li><li><strong>Image Selector:</strong> div.s-item__image-wrapper.image-treatment</li><li><strong>Price Selector: </strong>div.s-item__details.s-item__detail — primary</li><li><strong>Seller Selector:</strong> span.s-item__seller-info-text</li></ul><p>Okay, now let&#39;s execute our scenario:</p><ul><li><strong>Import the necessary modules.</strong></li></ul><pre>...<br>from selenium.webdriver.common.by import By<br>from selenium.webdriver.support.wait import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC</pre><ul><li><strong>define all the elements:</strong></li></ul><pre>URL = &#39;https://www.ebay.com/sch/i.html?_from=R40&amp;_nkw=laptop&amp;_sacat=0&amp;rt=nc&amp;LH_ItemCondition=1000&amp;RAM%2520Size=16%2520GB&amp;_dcat=177&amp;_ipg=240&#39;<br><br>container_selector = &#39;ul.srp-results.srp-list.clearfix&#39;<br>product_selector =&#39;div.s-item__wrapper.clearfix&#39;<br>link_selector = &#39;a.s-item__link&#39;<br>title_selector = &#39;div.s-item__title&#39;<br>price_selector = &#39;div.s-item__detail.s-item__detail--primary&#39;<br>seller_selector = &#39;span.s-item__seller-info-text&#39;<br>image_selector = &#39;div.s-item__image-wrapper.image-treatment&#39;<br><br><br>if __name__ == &#39;__main__&#39;:<br>    ...</pre><ul><li><strong>Navigate to the URL and wait for the container</strong></li></ul><pre>if __name__ == &#39;__main__&#39;:<br>    ...<br>    # Open the browser with Selenium and navigate to the URL<br>    driver.get(URL)<br>    # Wait for container present on the DOM of a page and visible with 15 second timeout<br>    WebDriverWait(driver, 15).until(EC.visibility_of_element_located((By.CSS_SELECTOR, container_selector)))<br>    <br>    # Quit the browser<br>    driver.quit()</pre><p><strong>WebDriverWait:</strong> Used to instruct Selenium to wait for certain conditions to be met before proceeding with the script.</p><p><strong>15</strong>: Timeout value in seconds, used to wait for the condition to become true before throwing a TimeoutException.</p><p><strong>Until:</strong> It waits until the condition is met or the timeout expires.</p><p><strong>EC:</strong> This is an alias for the expected_conditions module in Selenium, which provides various expected conditions that you can use with WebDriverWait.</p><p><strong>Presence Of Element Located</strong>: This is a specific expected condition that checks for the visibility of an element on the page.</p><p><strong>By</strong>: A class that represents a mechanism for locating elements on a web page. example: By.ID, By.CSS_SELECTOR, By.XPATH, By.CLASS_NAME, etc.</p><p><strong>Quit:</strong> Used to completely terminate the WebDriver session and close all associated browser windows, tabs, and processes.</p><ul><li><strong>Extract product title.</strong></li></ul><pre>if __name__ == &#39;__main__&#39;:<br>    ...<br>    # find 1 element of container<br>    container = driver.find_element(By.CSS_SELECTOR, container_selector) <br>    # find multiple element of product<br>    products = container.find_elements(By.CSS_SELECTOR, product_selector)<br>    # extract title with python list comprehension<br>    titles = [item.find_element(By.CSS_SELECTOR, title_selector).text for item in products]<br>    # example output: [&#39;title1&#39;,&#39;title2&#39;]<br>    print(title)<br>    ...</pre><p><strong>Find Element:</strong> used to find a single element.</p><p><strong>By.CSS_SELECTOR:</strong> Using a CSS selector to identify the element.</p><p><strong>.text: </strong>Access the text content of each found title element.</p><p><strong>products.find_elements:</strong> Used to locate multiple elements on the web page that match the specified locator strategy and value.</p><ul><li><strong>Extract product price</strong></li></ul><p>If we take a look at the price_selector, there’s an element inside, which is <strong>‘span.s-item__price’.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QsXPtdcDnSI6PjJ_NvJoZg.png" /></figure><p>Because there’s another element inside it, we have to change our price_selector to be like this.</p><pre>price_selector = &#39;div.s-item__detail.s-item__detail--primary span.s-item__price&#39;</pre><p>Yes, in Selenium, we can nested the CSS Selectors like the example above.</p><p>It’s actually fine to keep the price_selector as before, but the problem is we have to make sure that the attribute value (in this case, the class attribute value of div) is unique, In other words, There is no other set of data with his name. If there were, then the price data would be inaccurate.</p><pre>if __name__ == &#39;__main__&#39;:<br>    ...<br>    prices = [item.find_element(By.CSS_SELECTOR, price_selector).text for item in products]<br>    print(titles)<br>    print(prices)<br>    ...</pre><ul><li><strong>Extract product seller.</strong></li></ul><pre>if __name__ == &#39;__main__&#39;:<br>    ...<br>    sellers = [item.find_element(By.CSS_SELECTOR, seller_selector).text for item in products]<br>    print(titles)<br>    print(prices)<br>    print(sellers)<br>    ...</pre><ul><li><strong>Extract product link.</strong></li></ul><pre>if __name__ == &#39;__main__&#39;:<br>    ...<br>    links = [item.find_element(By.CSS_SELECTOR, link_selector).get_attribute(&#39;href&#39;) for item in products]<br>    print(titles)<br>    print(prices)<br>    print(sellers)<br>    print(links)<br>    ...</pre><p><strong>get_attribute:</strong> used to retrieve the value of a specific attribute of a web element.</p><ul><li>Extract product image URL.</li></ul><p>Let’s take a look at the image element again,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etcuiRyse_NIXNXuoDrxgQ.png" /></figure><p>Correct, there’s an image element inside the div, let’s change the CSS Selector.</p><pre>image_selector = &#39;div.s-item__image-wrapper.image-treatment img&#39;</pre><p>There’s a little difference here, we’re not chaining the image_selector to its attribute class, because there is no attribute class within the img tag, so we can just go to the tag instead of chaining it to any attribute.</p><pre>if __name__ == &#39;__main__&#39;:<br>    ...<br>    image_urls = [item.find_element(By.CSS_SELECTOR, image_selector).get_attribute(&#39;src&#39;) for item in products]<br>    print(titles)<br>    print(prices)<br>    print(sellers)<br>    print(links)<br>    print(image_urls)<br>    ...</pre><p>Congratulations! You have retrieved all the data through the console!</p><p><strong>Level Up: Exporting Your Data to CSV with Pandas</strong></p><p>You’ve scraped the web and extracted all the information, and now to level up your skill, we will export our scraped data into CSV with the Pandas library, let’s install and import the module.</p><pre>pip install pandas</pre><pre>import pandas as pd</pre><pre><br>if __name__ == &#39;__main__&#39;:<br>    ...<br>    dataFrame = pd.DataFrame(<br>        # Key: Value means Column with it&#39;s value<br>        {<br>            &#39;Product&#39;: titles,<br>            &#39;Price&#39;: prices,<br>            &#39;Seller&#39;: sellers,<br>            &#39;Link&#39;: links,<br>            &#39;Image URL&#39;: image_urls<br>        }<br>    )<br>    # Start from index 1<br>    dataFrame.index += 1<br>    # Export to csv with &#39;write&#39; mode<br>    dataFrame.to_csv(&#39;laptop_products.csv&#39;, mode=&#39;w&#39;)<br>   ...</pre><p><strong>pd.DataFrame({…}):</strong> Creating a pandas DataFrame, which is a powerful data structure for storing and manipulating tabular data.</p><p><strong>df.index += 1: </strong>This line modifies the default indices (row labels) of the DataFrame. It adds 1 to each index, starting them from 1 instead of 0.</p><p><strong>df.to_csv(‘laptop_products.csv’, mode=’w’):</strong> This line saves the DataFrame as a CSV (comma-separated values) file named “laptop_products.csv” with mode ‘w’ which will create a new file if it doesn’t exist or overwriting an existing one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CmyPDzhfZOeIuMAkARywsA.png" /></figure><p>Excellent! You already know how to simply export the list of data to CSV File.</p><p>The Complete Code:</p><pre>from selenium import webdriver<br>from selenium.webdriver.common.by import By<br>from selenium.webdriver.support.wait import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br>import pandas as pd<br>&#39;&#39;&#39;<br>    Selenium Website Scraping<br>    Target: eBay e-commerce website<br><br>    INFORMATION TO EXTRACT:<br>    - Product Title<br>    - Product Price<br>    - Product Seller<br>    - Product Image URL<br>    - Product Link<br>&#39;&#39;&#39;<br><br>URL = &#39;https://www.ebay.com/sch/i.html?_from=R40&amp;_nkw=laptop&amp;_sacat=0&amp;_fsrp=1&amp;RAM%2520Size=16%2520GB&amp;_dcat=177&amp;LH_ItemCondition=1000&amp;_ipg=240&amp;rt=nc&amp;LH_BIN=1&#39; #<br><br>container_selector = &#39;ul.srp-results.srp-list.clearfix&#39;<br>product_selector =&#39;div.s-item__wrapper.clearfix&#39;<br>link_selector = &#39;a.s-item__link&#39;<br>title_selector = &#39;div.s-item__title&#39;<br>price_selector = &#39;div.s-item__detail.s-item__detail--primary span.s-item__price&#39;<br>seller_selector = &#39;span.s-item__seller-info-text&#39;<br>image_selector = &#39;div.s-item__image-wrapper.image-treatment img&#39;<br><br>if __name__ == &#39;__main__&#39;:<br>    chrome_options = webdriver.ChromeOptions()  # Add options to chrome<br>    chrome_options.add_experimental_option(&#39;detach&#39;, True)  # Keep the browser open<br>    chrome_options.add_argument(&#39;--disk-cache-size=0&#39;)  # Disable cache<br>    chrome_options.add_argument(&#39;--blink-settings=imagesEnabled=false&#39;)  # Disable images<br>    chrome_options.add_argument(&#39;--headless&#39;)  # Enable headless mode<br><br>    driver = webdriver.Chrome(options=chrome_options)<br>    driver.get(URL)  # Open the browser and navigate to the URL<br>    WebDriverWait(driver, 15).until(EC.visibility_of_element_located((By.CSS_SELECTOR, container_selector)))  # Wait for container present on the DOM of a page and visible with 15 second timeout<br>    container = driver.find_element(By.CSS_SELECTOR, container_selector)<br>    products = container.find_elements(By.CSS_SELECTOR, product_selector)<br>    titles = [item.find_element(By.CSS_SELECTOR, title_selector).text for item in products]<br>    prices = [item.find_element(By.CSS_SELECTOR, price_selector).text for item in products]<br>    sellers = [item.find_element(By.CSS_SELECTOR, seller_selector).text for item in products]<br>    links = [item.find_element(By.CSS_SELECTOR, link_selector).get_attribute(&#39;href&#39;) for item in products]<br>    image_urls = [item.find_element(By.CSS_SELECTOR, image_selector).get_attribute(&#39;src&#39;) for item in products]<br>    <br>    print(titles)<br>    print(prices)<br>    print(sellers)<br>    print(links)<br>    print(image_urls)<br><br>    dataFrame = pd.DataFrame(<br>        {<br>            &#39;Product&#39;: titles,<br>            &#39;Price&#39;: prices,<br>            &#39;Seller&#39;: sellers,<br>            &#39;Link&#39;: links,<br>            &#39;Image URL&#39;: image_urls<br>        }<br>    )<br>    dataFrame.index += 1<br>    dataFrame.to_csv(&#39;laptop_products.csv&#39;, mode=&#39;w&#39;)<br>    driver.quit()</pre><p>Remember, This guide is just the first step on your web scraping journey. Keep learning, keep exploring, and keep challenging yourself. There’s a whole world of data out there waiting to be unlocked! You can Explore more about the By Class such as By.ID, By.XPATH, By.CLASS_NAME, etc, and you’ll be amazed at what you will achieve afterwards!</p><p>I hope this guide has been helpful and inspiring! If you have any questions or suggestions, feel free to leave a comment below. And remember, the web scraping community is always happy to help, so don’t hesitate to reach out, But stay tuned, because we’re just getting started! My upcoming tutorials will tackle advanced techniques like handling scrolling in page, navigating complex websites, and etc. Get ready to level up your data scraping skills!</p><p><strong>Feel free to contact me!</strong><br>Email: <a href="/service/mailto:naufalmng@gmail.com">naufalmng@gmail.com</a><br>Github: <a href="http://github.com/naufalmng">github.com/naufalmng</a><br>Linkedin: <a href="http://linkedin.com/in/mnaufalhanif/">linkedin.com/in/mnaufalhanif/</a><br>Instagram: <a href="http://instagram.com/naufalh.apk">instagram.com/naufalh.apk</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dfa29fc37a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extract Telegram Messages with Sleuth: A Step-by-Step Guide]]></title>
            <link>https://naufaltechhub.medium.com/extract-telegram-messages-with-sleuth-a-step-by-step-guide-8b2285301af3?source=rss-1ea0ae4711e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b2285301af3</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[data-scraping]]></category>
            <category><![CDATA[data-mining]]></category>
            <dc:creator><![CDATA[Muhammad Naufal Hanif]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 00:42:01 GMT</pubDate>
            <atom:updated>2024-01-08T01:20:16.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCbuwfD2g73Ihza3cUILHA.png" /></figure><p>Greetings, fellow tech enthusiasts! Today, I embark on a journey to explore the powerful realm of data extraction from Telegram chats using a Python library called Telegram Sleuth. This nifty tool allows you to unravel the secrets hidden in your Telegram conversations, extracting messages, media, and metadata for in-depth analysis.</p><p>Do you ever wish you could analyze the messages from your Telegram chats? With the powerful open-source Sleuth library for Python, extracting and exploring your Telegram data is easy. In this step-by-step guide, we’ll walk through installing Sleuth, connecting it to your Telegram account, and exporting your messages. Let’s dig in!</p><h3>Step 1: Get Your Telegram API Credentials</h3><p>To start digging into your Telegram data, you’ll need to get an API ID and hash from Telegram.</p><p>Here’s how:</p><ul><li>Go to <a href="https://my.telegram.org/apps">https://my.telegram.org/apps</a> and log in with your phone number. Telegram will send a confirmation code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QT_gUgRyjxnEorAJ55yYaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*035LJkETY6bUoUzM6S3h-A.png" /><figcaption>OTP Sent by Telegram API</figcaption></figure><ul><li>Enter the code and you’ll see your API ID and hash. Copy these somewhere safe!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TiDEzo2z6psm3fRX6VfCtA.png" /></figure><h3>Step 2: Install the Sleuth Library</h3><p>With your credentials ready, Open your idea, navigate to your terminal and summon Sleuth with a simple spell:</p><pre>pip install telegram-sleuth</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*FORi_GjZPLWQaelY2s_gsw.png" /></figure><h3>Step 3: Initialize Sleuth and Connect to Telegram</h3><p>Import Sleuth and create a Sleuth object, pass your API credentials, target username, and any desired customizations:</p><pre>from telegram_sleuth import Sleuth<br><br>sleuth = Sleuth(<br>    api_id=&#39;123456678&#39;, <br>    api_hash=&#39;aSd12Gfd87H4JI2k&#39;,<br>    username=&#39;KotlinIndonesia&#39; <br>)</pre><p>Normally, you can find the username through the contact/group info, In this tutorial, I am targeting my kotlin group. You can also use the optional parameters in Sleuth,</p><ul><li><strong>Specifying a date range for data extraction:</strong></li></ul><p>To specify a date range for data extraction, you can use the start_date and end_date parameters. For example, to extract data from a chat from November 20, 2023 to November 21, 2023:</p><pre>sleuth = Sleuth(<br>    ...,<br>    start_date=&#39;2023-11-20&#39;,<br>    end_date=&#39;2023-11-21&#39;<br>)</pre><ul><li><strong>Specifying a download path for media files:</strong></li></ul><p>To specify a download path for media files, you can use the download_path parameter. For example, I’ll download media files to the folder C:\Users\naufa\Downloads\sleuth:</p><pre>sleuth = Sleuth(<br>    ...,<br>    download_path=r&#39;C:\Users\naufa\Downloads\sleuth&#39;<br>)</pre><p><strong>What is r mean?</strong></p><p>The r before the string in download_path is used to create a raw string literal in Python. A raw string literal is prefixed with the letter &#39;r&#39; and is used to suppress the interpretation of backslashes (\). In a regular string literal, backslashes are used for escaping special characters (like newline \n or tab \t).</p><ul><li><strong>Printing messages to the console as they are extracted:</strong></li></ul><p>To print messages to the console as they are extracted, you can use the print_to_console parameter. For example, to print messages to the console as they are extracted, you can use the following code:</p><pre>sleuth = Sleuth(<br>    ...,<br>    print_to_console=True<br>)<br>&#39;&#39;&#39;<br>Example Output:<br>  2023-11-20 15:32:10+00:00 - john_doe: Hello everyone!<br>  2023-11-20 15:35:12+00:00 - john_doe sent a image: downloads/images/image1.jpg<br>&#39;&#39;&#39;</pre><p>Here’s the complete sleuth object with all the optional parameters:</p><pre>sleuth = Sleuth(<br>    api_id=&#39;123456678&#39;,<br>    api_hash=&#39;aSd12Gfd87H4JI2k&#39;,<br>    username=&#39;KotlinIndonesia&#39;,<br>    start_date=&#39;2023-11-20&#39;,  <br>    end_date=&#39;2023-11-21&#39;,   <br>    download_path=r&#39;C:\Users\naufa\Downloads\sleuth&#39;, <br>    print_to_console=True<br>)</pre><h3>Step 4: Extract Messages and Media</h3><p>To extract the data, call the dig() method:</p><pre>data = sleuth.dig()</pre><p>This returns a dictionary with the extracted messages, media, and metadata!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5Y_SYnCf9q4xQNoszp2rw.png" /><figcaption>Printed Extracted Data In the Console</figcaption></figure><h3>Step 5: Export Data to CSV</h3><p>To export the structured data to CSV, use export_to_csv():</p><pre>sleuth.export_to_csv(r&#39;C:\Users\naufa\Downloads\sleuth\kotlin_indonesia.csv&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Yr_u0QPuhySsP81N7mFvQ.png" /></figure><p>Voila! Now you’ve got a CSV file to explore and analyze as you wish!</p><p>Here’s the complete code snippet:</p><pre>from telegram_sleuth import Sleuth<br><br>sleuth = Sleuth(<br>    api_id=&#39;123456678&#39;,<br>    api_hash=&#39;aSd12Gfd87H4JI2k&#39;,<br>    username=&#39;KotlinIndonesia&#39;,<br>    start_date=&#39;2023-11-20&#39;,  <br>    end_date=&#39;2023-11-21&#39;,   <br>    download_path=r&#39;C:\Users\naufa\Downloads\sleuth&#39;, <br>    print_to_console=True<br>)<br><br>data = sleuth.dig()<br><br>sleuth.export_to_csv(&#39;kotlin_indonesia.csv&#39;)</pre><p>In conclusion, Telegram Sleuth empowers you to navigate the intricacies of Telegram chats effortlessly. If you encounter any mystical challenges or seek guidance, reach out to the wise sages at naufalmng@gmail.com or commune with fellow adventurers on the <a href="https://github.com/naufalmng/telegram-sleuth/issues">GitHub page</a>.</p><p>May your data extraction endeavours be fruitful, and may the Telegram Sleuth be ever in your favour! 🕵️‍♂️🔍</p><p>Sleuth provides powerful capabilities to unlock insights from your messaging history. Give it a try on your Telegram groups or chats and</p><p>Let’s Start Sleuthing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b2285301af3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Java to Python: Mastering Object-Oriented Programming in Python for Intermediate Developers]]></title>
            <link>https://naufaltechhub.medium.com/from-java-to-python-mastering-object-oriented-programming-in-python-for-intermediate-developers-14771435b270?source=rss-1ea0ae4711e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/14771435b270</guid>
            <category><![CDATA[object-oriented-program]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Muhammad Naufal Hanif]]></dc:creator>
            <pubDate>Tue, 26 Dec 2023 05:50:28 GMT</pubDate>
            <atom:updated>2023-12-26T05:50:28.734Z</atom:updated>
            <content:encoded><![CDATA[<p>Object-oriented programming (OOP) is a programming paradigm that uses objects as a foundation unit for developing programs. OOP have a lot of advantages, such as simplicity in handling and program development, along with increased code reusability.</p><p>Neither Java nor Python are programming languages that support OOP. However, there are noticeable differences between these two languages. Java is a programming language that is statically-typed, while Python is dynamically-typed. this means that data type in Java must be explicitly determined, whereas, in Python, the interpreter will automatically determine the data type from variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*fMEmoXUCOC11789h13sh7Q.png" /><figcaption>Source: <a href="https://www.linkedin.com/pulse/power-couple-using-java-python-advanced-applications-invicktusinc/">Linkedin</a></figcaption></figure><p>Let’s dive into the OOP Concept in Python, shall we?</p><p>In Python, most of the OOP Concepts are similar to Java OOP, here are some <strong>OOP Concepts in Python</strong>:</p><ul><li><strong>Class:</strong> Blueprints to create an object.</li><li><strong>Object:</strong> Instance of the class.</li><li><strong>Attribute:</strong> Property of an object.</li><li><strong>Method: </strong>Function that is associated with an object.</li><li><strong>Inheritance: </strong>Allows one class to inherit attributes and methods from another class.</li><li><strong>Polymorphism: </strong>Allows objects of different classes to respond to the same message in different ways.</li><li><strong>Encapsulation: </strong>Wraps data and functions in a single unit.</li></ul><p><strong>OOP Differences in Java and Python:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*PyGxehZ3NPRD0Ktuoa-Mdg.png" /><figcaption>OOP Differences</figcaption></figure><p><strong>Examples of basic OOP Concepts:</strong></p><p>Here is some example of the <strong>Person</strong> class that is used to keep information about the person, such as name and age:</p><pre>class Person:<br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age<br><br>    def say_hello(self):<br>        print(f&quot;Hello, my name is {self.name}. I am {self.age} years old.&quot;)<br><br><br>person1 = Person(&quot;John Doe&quot;, 30)<br>person2 = Person(&quot;Jane Doe&quot;, 25)<br><br>print(person1.name)<br># John Doe<br><br>print(person2.age)<br># 25<br><br>person1.say_hello()<br># Hello, my name is John Doe. I am 30 years old.<br><br>person2.say_hello()<br># Hello, my name is Jane Doe. I am 25 years old.</pre><p>It’s quite similar to Java, right? This is even more concise than Java, don’t you think?</p><p>This is an example of not using the Class keyword in Python:</p><pre>def Person(name, age):<br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age<br><br>    def say_hello(self):<br>        print(&quot;Hello, my name is {} and I am {} years old.&quot;.format(self.name, self.age))<br><br>person1 = type(&quot;Person&quot;, (), {<br>    &quot;name&quot;: name,<br>    &quot;age&quot;: age,<br>    &quot;say_hello&quot;: say_hello<br>})<br><br>person1.say_hello()</pre><p>To create a Person class without the Class keyword, we use the type() function with two arguments:</p><p>1. The first argument is the class name: “Person”.</p><p>2. The second argument is a dictionary that defines the class attributes and methods:</p><ul><li><strong>name:</strong> The name attribute of type string.</li><li><strong>age:</strong> The age attribute of integer type.</li><li><strong>say_hello():</strong> The say_hello() method that accepts one argument self.</li></ul><p>Once the Person class is created, we can create objects from that class using the operator ().</p><p><strong>Examples of advanced OOP concepts:</strong></p><p>Here is an example of the <strong>Shape </strong>class (known as abstract class) used as the parent of the <strong>Rectangle</strong> and <strong>Circle</strong> classes:</p><pre>import math<br><br><br>class Shape:<br>    def __init__(self, name):<br>        self.name = name<br><br>    def get_area(self):<br>        raise NotImplementedError<br><br># Inheriting the shape class<br>class Rectangle(Shape):<br>    def __init__(self, name, width, height):<br>        super().__init__(name)<br>        self.width = width<br>        self.height = height<br><br>    def get_area(self):<br>        return self.width * self.height<br><br># Inheriting the shape class<br>class Circle(Shape):<br>    def __init__(self, name, radius):<br>        super().__init__(name)<br>        self.radius = radius<br><br>    def get_area(self):<br>        return math.pi * self.radius ** 2<br><br><br>rectangle = Rectangle(&quot;Rectangle&quot;, 10, 20)<br>circle = Circle(&quot;Circle&quot;, 10)<br><br>print(rectangle.get_area())<br># 200<br><br>print(circle.get_area())<br># 314.1592653589793</pre><p>The Rectangle and Circle classes are subclasses of the Shape class. The Rectangle class has two attributes, namely width and height. The Circle class has one attribute, namely radius. Both of them inherit the shape class (parent class).</p><p>Examples of OOP App:</p><p>The following is an example of a guess number game.</p><pre>import random<br><br><br>class Game:<br>    def __init__(self):<br>        self.number = random.randint(1, 100)<br>        self.guesses = 0<br><br>    def guess(self, guess):<br>        self.guesses += 1<br>        if guess == self.number:<br>            print(&quot;You guessed correctly! It took you {} guesses.&quot;.format(self.guesses))<br>            return True<br>        elif guess &lt; self.number:<br>            print(&quot;Your guess is too low.&quot;)<br>            return False<br>        else:<br>            print(&quot;Your guess is too high.&quot;)<br>            return False<br><br><br>game = Game()<br>user_input = int(input(&quot;Guess a number between 1 and 100: &quot;))<br>while not game.guess(user_input):<br>    pass</pre><p>This program uses the Game class to create a number guessing game. The Game class has two attributes, namely number and guesses. The class also has one method, namely guess().</p><p>The guess() method is used to process the player’s guess. This method will check whether the player’s guess is correct. If the player’s guess is correct, then this method will print a success message and return True. If the player’s guess is wrong, then this method will print an error message and return False.</p><p>In this program, the Game class is used to store the number that the player must guess, as well as the number of guesses that the player has made. The guess() method is used to process the player’s guess and print a success or error message.</p><p>Object-oriented programming (OOP) is a powerful and versatile programming paradigm. By mastering OOP, you can write programs that are more modular, reusable, and maintainable.</p><p>Here are some tips for mastering OOP in Python:</p><ul><li>Start by learning basic OOP concepts, such as classes, objects, attributes, and methods.</li><li>Practice using the OOP examples given in this article.</li><li>Try creating your own program using OOP.</li></ul><p>By following the tips above, you will be able to master OOP in Python quickly and easily.</p><p>Hopefully, this article is useful for you! If you have any questions or comments, feel free to leave a message below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14771435b270" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>