<?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 Parker Montgomery on Medium]]></title>
        <description><![CDATA[Stories by Parker Montgomery on Medium]]></description>
        <link>https://medium.com/@pumpkingee?source=rss-de43916695e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0cpGcOlFMhqYKPKZRLZ7Uw.png</url>
            <title>Stories by Parker Montgomery on Medium</title>
            <link>https://medium.com/@pumpkingee?source=rss-de43916695e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:53:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pumpkingee/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[You can always find all relevant and valuable information about products, sellers, reviews…]]></title>
            <link>https://medium.com/@pumpkingee/you-can-always-find-all-relevant-and-valuable-information-about-products-sellers-reviews-b20cad2e9b3a?source=rss-de43916695e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b20cad2e9b3a</guid>
            <category><![CDATA[browserless]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Parker Montgomery]]></dc:creator>
            <pubDate>Fri, 08 Nov 2024 06:04:52 GMT</pubDate>
            <atom:updated>2024-11-08T06:06:31.711Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YL5KJ-gN0i0hbkOK" /></figure><p>You can always find all relevant and valuable information about products, sellers, reviews, ratings, specials, news, etc. on Amazon. Whether it is a seller doing market research or an individual collecting data, using a high-quality, convenient and fast tool will help you to accurately crawl various information on Amazon to a great extent.</p><h3>Why Is Scraping Amazon Product Data Important?</h3><p>Amazon gathers valuable information in one place: products, reviews, ratings, exclusive offers, news, etc. Therefore, data scraping on Amazon will largely avoid time-consuming and labor-intensive problems. As a business, using Amazon product scraper can bring you at least the following 4 significant benefits:</p><ul><li>Understand the prices in the local or even global market and compare prices</li><li>Analyze the differences with competitors</li><li>Identify target groups</li><li>Improve product image</li><li>Predict user needs</li><li>Collect customer information</li></ul><h3>Typical Reasons to Scrape Amazon Products</h3><ul><li>Monitor Competitor Pricing and Products</li><li>Understand Market Trends</li><li>Optimize Marketing Strategies</li><li>Improve Product Listings</li><li>Price Optimization</li><li>Enhance Product Research</li><li>Track Customer Sentiment</li></ul><h3>Does Browserless Help to Build an Amazon Product Scraper?</h3><p>Headless browsers are excellent in performing automated work? That’s right, we will use Nstbrowser’s most powerful headless browser service: <strong>Browserless to crawl Amazon product information.</strong></p><p>When crawling Amazon product data, we always encounter a series of severe challenges such as <strong>robot detection, verification code recognition, and IP blocking. Using Browserless can fully avoid these headaches!</strong></p><p>Nstbrowser’s Browserless provides real user browser fingerprints, and each fingerprint is unique. In addition, participating in our subscription plan can achieve full captcha bypass, escorting your unimpeded access experience.</p><p>Join our <a href="https://discord.gg/sVcExjq7bt"><strong>Discord</strong></a> referral program to share <strong>$1,500 in cash</strong> now!</p><blockquote><a href="https://www.youtube.com/watch?v=DTMnewNki-0"><strong>Find more details about Browserless in our video!</strong></a></blockquote><h3>How Can We Scrap Amazon Product Data?</h3><p>Without further ado, let’s now officially start using Browserless for data crawling!</p><h3>Prerequisites</h3><p>Before we start, we need to connect to the Browserless service. Using <a href="https://www.nstbrowser.io/en/product/browserless"><strong>Browserless</strong></a> can solve complex web scraping and large-scale automation tasks, and you can really enjoy the fully managed cloud deployment.</p><p>Browserless adopts a browser-centric concept, provides powerful headless deployment capabilities, and provides higher performance and reliability. For more information about Browserless, you can refer to our relevant <a href="https://apidocs.nstbrowser.io/doc-639323"><strong>documentation</strong></a>.</p><p>Get the API KEY and go to the Browserless menu page of the Nstbrowser client, or you can <a href="https://app.nstbrowser.io/app/browserless">click here</a> to access it directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sM7deOR_ORRga_p7.png" /></figure><h3>Install Puppeteer and connect to Browserless</h3><ol><li>Install Puppeteer. The lighter puppeteer-core is a better choice.</li></ol><pre># pnpm<br>pnpm i puppeteer-core<br># yarn<br>yarn add puppeteer-core<br># npm<br>npm i --save puppeteer-core</pre><p>2. We have prepared the code to call Browserless. You only need to fill in the apiKey and proxy to start the subsequent Amazon product scraper operation:</p><pre>const apiKey = &quot;your ApiKey&quot;; // required<br>const config = {<br>    proxy: &#39;your proxy&#39;, // required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080<br>    // platform: &#39;windows&#39;, // support: windows, mac, linux<br>    // kernel: &#39;chromium&#39;, // only support: chromium<br>    // kernelMilestone: &#39;128&#39;, // support: 128<br>    // args: {<br>    //     &quot;--proxy-bypass-list&quot;: &quot;detect.nstbrowser.io&quot;<br>    // }, // browser args<br>    // fingerprint: {<br>    //     userAgent: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36&#39;, // userAgent supportted since v0.15.0<br>    // },<br>};<br>const query = new URLSearchParams({<br>    token: apiKey, // required<br>    config: JSON.stringify(config),<br>});<br>const browserlessWSEndpoint = `https://less.nstbrowser.io/connect?${query.toString()}`;</pre><h3>Start crawling</h3><h4>Step1: Check the target page</h4><p>Before crawling, we can try to go to https://www.amazon.com/. If it is the first time visiting, there is a high probability that a verification code will appear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HPb8TQX2bZh0GvZj.png" /></figure><p>But it doesn’t matter, we don’t have to go to great lengths to find a verification code decoding tool. At this time, you only need to visit the Amazon domain name in your region or the region of your proxy, and the verification code will not be triggered.</p><p>For example, let’s visit: https://www.amazon.co.uk/: the Amazon domain name in the UK. We can see the page smoothly, then try to enter the product keyword we want in the top search bar or directly visit through the URL, like:</p><pre>https://www.amazon.co.uk/s?k=shirt</pre><p>The value after /s?k= in the URL is the keyword of the product. By accessing the above URL, you will see shirt-related products on Amazon. Now you can open the &quot;Developer Tools&quot; (F12) to check the HTML structure of the page and confirm the data we need to crawl later by positioning the cursor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z5lvKp2rrvDpqGUM.png" /></figure><h4>Step2: Scriptwriting</h4><p>First, I added a string of code at the top of the script. The following code uses the first script parameter as the Amazon product keyword, and subsequent scripts will also use this parameter to crawl:</p><pre>const productName = process.argv.slice(2);<br><br>if (productName.length !== 1) {<br>  console.error(&#39;product name CLI arguments missing!&#39;);<br>  process.exit(2);<br>}</pre><p>Next, we need to:</p><ul><li>Import Puppeteer and connect to Browserless</li><li>Go to the product query result page corresponding to Amazon</li><li>Add a screenshot to verify whether the access is successful</li></ul><pre>import puppeteer from &quot;puppeteer-core&quot;;<br><br>const browser = await puppeteer.connect({<br>  browserWSEndpoint: browserlessWSEndpoint,<br>  defaultViewport: null,<br>})<br>console.info(&#39;Connected!&#39;);<br><br>const page = await browser.newPage();<br><br>await page.goto(`https://www.amazon.co.uk/s?k=${productName}`);<br><br>// Add screenshots to facilitate subsequent troubleshooting<br>await page.screenshot({ path: &#39;amazon_page.png&#39; })</pre><p>Now we use page.$$ to get a list of all products, loop through the product list, and get the relevant data one by one in the loop. Then collect this data into the productDataList array and print it:</p><p>JavaScript Copy</p><pre>// Get the container element of all search results<br>const productContainers = await page.$$(&#39;div[data-component-type=&quot;s-search-result&quot;]&#39;)<br><br>const productDataList = []<br><br>// Get various information about the product: title, rating, image link, price<br>for (const product of productContainers) {<br><br>  async function safeEval(selector, evalFn) {<br>    try {<br>      return await product.$eval(selector, evalFn);<br>    } catch (e) {<br>      return null;<br>    }<br>  }<br><br>  const title = await safeEval(&#39;.s-title-instructions-style &gt; h2 &gt; a &gt; span&#39;, node =&gt; node.textContent)<br>  const rate = await safeEval(&#39;a &gt; i.a-icon.a-icon-star-small &gt; span&#39;, node =&gt; node.textContent)<br>  const img = await safeEval(&#39;span[data-component-type=&quot;s-product-image&quot;] img&#39;, node =&gt; node.getAttribute(&#39;src&#39;))<br>  const price = await safeEval(&#39;div[data-cy=&quot;price-recipe&quot;] .a-offscreen&#39;, node =&gt; node.textContent)<br><br>  productDataList.push({ title, rate, img, price })<br>}<br><br>console.log(&#39;amazon_product_data_list :&#39;, productDataList);<br><br>await browser.close();const productDataList = []</pre><p>Running the script:</p><pre>node amazon.mjs shirt</pre><p>If successful, the following will be printed on the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/0*2MkCZf8EzJuoY5cM.png" /></figure><h4>Step3: Output the crawled data as a JSON file</h4><p>Obviously, in order to better analyze the data, it is not enough to just print the data in the console. Here is a simple example: quickly convert a JS object to a JSON file through the fs module:</p><pre>import fs from &#39;fs&#39;<br><br>function saveObjectToJson(obj, filename) {<br>  const jsonString = JSON.stringify(obj, null, 2)<br>  fs.writeFile(filename, jsonString, &#39;utf8&#39;, (err) =&gt; {<br>    err ? console.error(err) : console.log(`File saved successfully: ${filename}`);<br>  });<br>}<br><br>saveObjectToJson(productDataList, &#39;amazon_product_data.json&#39;)</pre><p>Ok, let’s take a look at our complete code:</p><pre>import puppeteer from &quot;puppeteer-core&quot;;<br>import fs from &#39;fs&#39;<br><br>const productName = process.argv.slice(2);<br><br>if (productName.length !== 1) {<br>  console.error(&#39;product name CLI arguments missing!&#39;);<br>  process.exit(2);<br>}<br><br>const apiKey = &quot;your ApiKey&quot;; // &#39;your proxy&#39;<br><br>const config = {<br>  proxy: &#39;your proxy&#39;, // required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080<br>  // platform: &#39;windows&#39;, // support: windows, mac, linux<br>  // kernel: &#39;chromium&#39;, // only support: chromium<br>  // kernelMilestone: &#39;128&#39;, // support: 128<br>  // args: {<br>  //     &quot;--proxy-bypass-list&quot;: &quot;detect.nstbrowser.io&quot;<br>  // }, // browser args<br>  // fingerprint: {<br>  //     userAgent: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36&#39;, // userAgent supportted since v0.15.0<br>  // },<br>};<br><br>const query = new URLSearchParams({<br>  token: apiKey, // required<br>  config: JSON.stringify(config),<br>});<br><br>const browserlessWSEndpoint = `https://less.nstbrowser.io/connect?${query.toString()}`;<br><br>const browser = await puppeteer.connect({<br>  browserWSEndpoint: browserlessWSEndpoint,<br>  defaultViewport: null,<br>})<br>console.info(&#39;Connected!&#39;);<br><br>const page = await browser.newPage();<br><br>await page.goto(`https://www.amazon.co.uk/s?k=${productName}`);<br><br>// Add screenshots to facilitate subsequent troubleshooting<br>await page.screenshot({ path: &#39;amazon_page.png&#39; })<br><br>// Get the container element of all search results<br>const productContainers = await page.$$(&#39;div[data-component-type=&quot;s-search-result&quot;]&#39;)<br><br>const productDataList = []<br><br>// Get various information about the product: title, rating, image link, price<br>for (const product of productContainers) {<br><br>  async function safeEval(selector, evalFn) {<br>    try {<br>      return await product.$eval(selector, evalFn);<br>    } catch (e) {<br>      console.log(`Error fetching ${selector}:`, e);<br>      return null;<br>    }<br>  }<br><br>  const title = await safeEval(&#39;.s-title-instructions-style &gt; h2 &gt; a &gt; span&#39;, node =&gt; node.textContent)<br>  const rate = await safeEval(&#39;a &gt; i.a-icon.a-icon-star-small &gt; span&#39;, node =&gt; node.textContent)<br>  const img = await safeEval(&#39;span[data-component-type=&quot;s-product-image&quot;] img&#39;, node =&gt; node.getAttribute(&#39;src&#39;))<br>  const price = await safeEval(&#39;div[data-cy=&quot;price-recipe&quot;] .a-offscreen&#39;, node =&gt; node.textContent)<br><br>  productDataList.push({ title, rate, img, price })<br>}<br><br>function saveObjectToJson(obj, filename) {<br>  const jsonString = JSON.stringify(obj, null, 2)<br>  fs.writeFile(filename, jsonString, &#39;utf8&#39;, (err) =&gt; {<br>    err ? console.error(err) : console.log(`File saved successfully: ${filename}`);<br>  });<br>}<br><br>saveObjectToJson(productDataList, &#39;amazon_product_data.json&#39;)<br><br>console.log(&#39;amazon_product_data_list :&#39;, productDataList);<br><br>await browser.close();</pre><p>Now, after running the script, you can not only see the console print, but also theamazon_product_data.json file written under the current path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/0*eHS5zAG3IW4gSc8W.png" /></figure><h3>Check the Browserless dashboard</h3><p>You can view statistics for recent requests and remaining session time in the Browserless menu of the Nstbrowser client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vtm2XNY7JhEpaP3t.png" /></figure><h3>Nstbrowser RPA: An Easier Way to Build Your Amazon Scraper</h3><p>Using RPA tools to crawl web data is a common method of data collection. Using RPA tools can greatly improve the efficiency of data collection and reduce the cost of collection. <a href="https://www.nstbrowser.io/zh/rpa"><strong>Nstbrowser RPA</strong></a> function can provide you with the best RPA experience and the best work efficiency.</p><p><strong>After reading this tutorial, you will:</strong></p><ul><li>Understand how to use RPA for data collection</li><li>Understand how to save the data collected by RPA</li></ul><h3>Preparation</h3><p>First, you need to have an Nstbrowser account, and then log in to the <a href="https://app.nstbrowser.io/account/login"><strong>Nstbrowser client</strong></a>, enter the workflow page of the RPA module, and click New Workflow.</p><p>Now, we can start configuring the RPA crawling workflow based on Amazon product search results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*232NmmqvWGw5jY7F.png" /></figure><h3>Step 1. Visit the target website</h3><ul><li>We need to visit our target website: https://www.amazon.co.uk;</li><li>You can also use the Amazon main site directly: https://www.amazon.com/, but you need to manually process the verification code for the first visit;</li><li>Use the Goto Url node, configure the website URL, and you can visit the target website:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*umrWTKMxQm6xUkV4.png" /></figure><h3>Step 2. Search target content</h3><p>This time we will not use the method of querying the corresponding product through the URL, but use RPA to help enter the input box on the homepage and then trigger the query jump. This will not only make us more familiar with the operation of RPA, but also avoid site risk control to a greater extent.</p><p>Okay, after reaching the target website, we need to search for the target address first. Here we need to use the Chrome Devtool tool to locate the HTML element.</p><ul><li>Open the Devtool tool and select the search box with the mouse. We can see:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uHDWOVR1NStFFcRf.png" /></figure><ul><li>Our target input box element has an id attribute, which can be used as a CSS selector to locate the input box.</li></ul><p>Add Input Content node:</p><ul><li>Select <strong>Selector</strong> in the Element option. This option uniformly selects <strong>Selector</strong>.</li><li>Fill in the CSS selector of the id we are located in the input box</li><li>and then enter the content we want to search for in the Content option.</li></ul><p>In this way, we have completed the action of entering the input box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OpH15m3H33Wb67Cg.png" /></figure><ul><li>Then use the Keyboard node to simulate the keyboard&#39;s enter action to search for products:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F4w5Inh7eLL1P119.png" /></figure><p>Because the search page will jump to a new page, we need to add a waiting action to ensure that we have successfully loaded the result page. Nstbrowser RPA provides two waiting behaviors: Wait Time and Wait Request.</p><ol><li><strong>Wait Time</strong>: used to wait for a period of time. You can choose a fixed time or a random time according to your specific situation.</li><li><strong>Wait Request</strong>: used to wait for the network request to end. Applicable to the situation of obtaining data through network requests.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ytTJv7JtlAcQnips.png" /></figure><h3>Step 3. Traversing the product list</h3><p>Okay, now we can successfully see the new product search page, and the next step is to crawl these contents.</p><p>By observation, we can find that Amazon’s search results are displayed in the form of a card list. This is a very classic display method:</p><p>Similarly, open the Devtool tool and locate each data in the card:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TgssaToDH84B2Zr_.png" /></figure><p>Because each item in the card list is an HTML element, we need to use the Loop Element node to traverse all the query results. We fill in the CSS selector of the product list in <strong>Selector</strong> and select Element Object for <strong>Data Type</strong>, which means getting the target element and saving it as an element object to a variable. Set the variable name to product through <strong>Data Save Variable</strong>, and save the index as productIndex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BlFwbKkR_kuKpK_j.png" /></figure><h3>Step 4. Get data</h3><p>Next, we need to process each traversed element and get the information we need from the <strong>product</strong>. We get the title element of the product. Here we need to use the Get Element Data node to get it and finally save it as the variable title.</p><p>Select Children as <strong>Data Type</strong>, which means getting the child elements of the target element and saving it as an element object in the variable title. You need to fill in the element selector of the child element. The CSS selector entered here is naturally the CSS selector of the product title:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4UCib8HG3h7tCyTS.png" /></figure><p>Then we use the same method to convert the remaining product information: ratings, image links, and prices, all into RPA processes.</p><ul><li>Variable names and Children CSS selectors:</li></ul><pre>&#39;title&#39; .s-title-instructions-style &gt; h2 &gt; a &gt; span<br>&#39;rate&#39; a &gt; i.a-icon.a-icon-star-small &gt; span<br>&#39;img&#39; span[data-component-type=&quot;s-product-image&quot;] img<br>&#39;price&#39; div[data-cy=&quot;price-recipe&quot;] .a-offscreen</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pXOOg7xAtgW7mUz0.gif" /></figure><p>However, the variable data obtained above are actually HTML elements. We still need to process them to output the text in the HTML elements and prepare for subsequent data storage.</p><ol><li><strong>Set up the table</strong></li></ol><p>We need to</p><ul><li>Set up the table</li><li>And generate the corresponding Excel based on the fields of this table:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O05sePqEohcLZyuz.png" /></figure><p><strong>2. Get the text of the element</strong></p><p>Add the Get Element Data node again to output the variables obtained above as text and save them to the table variable for subsequent data storage. Select <strong>Data Type</strong> as Text to get the innerText of the target element. (The figure below shows the processing of the variable title)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BTLDMcwr1P17mtqC.png" /></figure><p><strong>3. Get the link to the image</strong></p><p>Then we use the same method to convert the product’s rating and price into the final text information.</p><p>The image link needs additional processing. Here we use the javascript node to get the image src of the current traversed product. Note that the index variable productIndex saved by the Loop Element node needs to be injected into the script and finally saved as the variable <strong>imgSrc</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ElxIugpR1U2N2NP2.png" /></figure><pre>return document.querySelectorAll(&#39;[data-image-latency=&quot;s-product-image&quot;]&#39;)[productIndex].getAttribute(&#39;src&#39;)</pre><p>Finally, we use the Set Variable node to store the variable <strong>imgSrc</strong> in the <strong>table</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7JiUe-kGpStGzRsh.png" /></figure><h3>Step 5. Save the result</h3><p>At this point, we have obtained all the data we want to collect, and it is time to save this data.</p><ul><li>Nstbrowser RPA provides two ways to save data: Save To File and Save To Excel.</li></ul><ol><li>Save To File provides three file types for you to choose from <strong>.txt</strong>, <strong>.CSV</strong>, and <strong>.JSON</strong>.</li><li>Save To Excel can only save data to <strong>Excel</strong> files.</li></ol><p>For easy viewing, we choose to save the collected data to Excel. Add the Save To Excel node, configure the file path and file name to be saved, select the table content to be saved, and you are done!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iSdX96Ohg44CLxss.png" /></figure><h3>Execute RPA</h3><p>Save the workflow we configured first, then you can run it directly on the current page, or return to the previous page, create new tasks, and click the Run button to run it. At this point, we can start collecting Amazon’s product data!</p><p>After the execution is completed, you can see the amazon-product-data.xlsx file generated on the desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0Kd0I8U_qVcSV8uI.png" /></figure><h3>The Bottom Lines</h3><p>The easiest way to scrape Amazon products is to build your own Amazon product scraper using Browserless. This most comprehensive tutorial article of 2024 clearly explains to you:</p><ul><li>The benefits of scraping Amazon products.</li><li>The powerful functions of Browserless Amazon product scraper.</li><li>How to create an easier scraper using Nstbrower’s RPA.</li></ul><p><strong>If you have special needs for Browserless, data scraping, or automation, please go to the official website of </strong><a href="https://www.nstbrowser.io/en"><strong>Nstbrowser</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b20cad2e9b3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Best anti-detect Browsers in 2024]]></title>
            <link>https://medium.com/@pumpkingee/5-best-anti-detect-browsers-in-2024-63c75c9d7226?source=rss-de43916695e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/63c75c9d7226</guid>
            <category><![CDATA[antidetect-browser]]></category>
            <dc:creator><![CDATA[Parker Montgomery]]></dc:creator>
            <pubDate>Thu, 31 Oct 2024 06:33:48 GMT</pubDate>
            <atom:updated>2024-10-31T06:33:48.904Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you found that your browser always provides you with a better browsing experience? However, you must know that websites usually use cookies to save your information and ensure a more comfortable browsing experience. Is this important? Actually, it’s not.</p><p>However, some websites will track your IP address and geographical location without your knowledge. How to deal with private information being stolen or tracked? This is exactly what this article can help you with!</p><p>We will introduce you to 5 powerful anti-detect browsers to help you solve the trouble of website monitoring!</p><p>Keep scrolling now!</p><h3>What Is an Anti-detect Browser?</h3><p>Anti-detect browsers have a well-understood approach: browsers + avoid detection. An anti-detection browser allows you to create independent browsing environments with its own digital fingerprints: different browser headers and other information used for network identification. As a result, websites cannot connect your real information to these environments.</p><p>For greater security and independence, you can integrate your own proxy with the anti-detection browser, but this requires additional costs.</p><h3>How Do We Choose an Antidetect Browser?</h3><p>If you’ve read this article, you’ve already started researching anti-detection browsers. Yes, as you can see, we can find dozens of them. Basically, each option varies in price and features. How to choose? Please think about the following questions:</p><p>1. <strong>What is the price I can accept?</strong> Quality costs money, so the best anti-detect browsers are usually expensive. However, there are some brands, such as Nstbrowser, that offer more profiles and related features at a lower price.</p><p>2. <strong>How many profiles do I need?</strong> Because when testing, I found that some anti-detection browsers, although they offer free packages, allow you to create up to 10 profiles.</p><p>3. <strong>Do I need departmental collaboration?</strong> You may often have some work that requires departmental collaboration. In this case, an anti-detect browser with cloud synchronization and profile synchronization will make your work easier.</p><h3>1. Nstbrowser: Free service, powerful functions</h3><p><strong>Verdict: </strong>🌟🌟🌟🌟🌟</p><ul><li>Free Plan: ✅</li><li>Customized Service</li><li>100000 profile creation</li><li>API: ✅</li><li>Special Features: <a href="https://apidocs.nstbrowser.io/doc-639323?nav=1">Browserless</a> &amp; Docker Container</li><li>Operation systems: macOS, Windows &amp; Linux</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8ljWblmO-lsQwiV2" /></figure><p>What attracts me most about <a href="https://www.nstbrowser.io/en"><strong>Nstbrowser</strong></a> is its free package:</p><ul><li>Unlimited profile creation.</li><li>Up to 2 team member seats.</li></ul><p>And Nstbrowser also provides separately billed rules. So that you can pay as you need, without paying expensive fixed packages.</p><p>The browser is also compatible with popular automation frameworks on the market, such as Puppeteer, Playwright and Selenium. Nstbrowser also promises to provide real fingerprint information to ensure that it will not be monitored by robots. If you need cloud browsers, Browserless and Docker container services, then Nstbrowser is your best choice.</p><p>In addition, using their <a href="https://www.nstbrowser.io/en/rpa-marketplace">RPA</a>, you can easily build your crawler programs, such as data filtering, automatic email sending, and web crawling. You don’t need any technical knowledge, you can solve it through simple board prevention. The most important thing is that they also promise to provide exclusive services, just tell them your needs.</p><h3>2. Multilogin: A reliable solution</h3><p><strong>Verdict:</strong> 🌟🌟🌟🌟</p><ul><li>Free plan: ❌</li><li>No separate pricing</li><li>The lowest plan only supports 10 profiles</li><li>API service: ✅</li><li>Special feature: Proxy integration</li><li>Operation systems: macOS, Windows, Linux</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nacH_zHWPrQKvNfV" /></figure><p><a href="https://multilogin.com/"><strong>Multilogin</strong></a> is known as the gold standard in the industry. It allows you to create multiple profiles, modify your digital browser fingerprint, and automatically integrate marketing tools. This Estonian company is one of the pioneers in the field, and they have a strong ability to manage multiple accounts.</p><p>However, Multilogin is one of the more expensive anti-detection browsers on the market. Plans that unlock features such as an unlimited number of team members and more proxy traffic start at $170. Otherwise, you can pay $31 per month for the basic plan, but this plan only includes 10 profiles, while competitors offer unlimited profiles for the same price.</p><h3>3. Octo Browser: Excellent multi-account anti-detect browser</h3><p><strong>Verdict: </strong>🌟🌟🌟🌟</p><ul><li>Free plan: ❌</li><li>No separate pricing</li><li>Create up to 1,200 profiles</li><li>API: ✅</li><li>Mostly basic functions</li><li>Operation systems: macOS, Windows &amp; Linux</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5prp7aE-q3VVi_Je" /></figure><p><a href="https://octobrowser.net/"><strong>Octo Browser</strong></a> is a fast and feature-rich multi-account browser. It excels in fingerprint management, teamwork, API automation, proxy integration, etc. However, Octo Browser is relatively new, so it is constantly being improved and perfected.</p><p>The browser basically has all the basic functions: team access function, custom fingerprint with more than 50 parameters, cookie and proxy management, etc. But if you need to use the API, you will need to pay for it.</p><h3>4. Adspower: an easy-to-use tool</h3><p>Verdict: 🌟🌟🌟🌟</p><ul><li>Free plan<strong>: </strong>❌</li><li>The free trial includes 5 browser profiles</li><li>Billed separately based on demand</li><li>API: ✅</li><li>Special feature: Proxy integration</li><li>Operation systems: macOS, Windows</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TGaF-h4lKNeOIC-K" /></figure><p><a href="https://www.adspower.com/"><strong>AdsPower</strong></a> is another reliable anti-detection browser provider. It is a Chinese service company designed to manage e-commerce and social media accounts. The biggest difference between Adspower and other browsers is its pricing rules: they only have a free trial version and customized packages on demand. Like Nstbrowser, you can pay according to your specific needs.</p><p>The browser also provides powerful automation features without the need for programming knowledge. For example, its RPA recorder can learn and replicate your workflow as you click on content, whether it is publishing, adding items to the shopping cart, etc.</p><h3>5. Kameleo: help to easily manage your profiles</h3><p>Verdict: 🌟🌟🌟🌟</p><ul><li>Free plan: ❌</li><li>Unlimited profile creation</li><li>All the plans can be refund</li><li>API: ✅</li><li>Special feature: Support the mobile system</li><li>Operation systems: Android, Windows</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6cFLab5rV8xWlW9O" /></figure><p><a href="https://kameleo.io/"><strong>Kameleo</strong></a> is a browser management app. All of their plans allow you to create unlimited Android and iOS profiles and use Selenium to automate the process. Kamelo also supports running both mobile and PC versions simultaneously. You can use it in all major web browsers: Firefox, Chrome, Safari, and Edge. This service provider also offers an Android app to change your mobile fingerprint and a way to forge canvas fingerprints.</p><p>However, it should be noted that their customer support is slow and the collaboration options are inconvenient. And the most annoying thing is that all data is stored locally, which greatly increases the burden on my local system.</p><h3>Choose Your Anti-detect Browser Now!</h3><p>No matter what website you visit, your browser will choose to automatically store your browsing history and usage footprints. For those who strictly protect their information, this is an invasion of privacy. For ordinary people, this will also interfere with their work to a certain extent.</p><p>Fortunately, with the help of a powerful anti-detection browser and proxy configuration, you can effectively avoid network tracking and information storage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63c75c9d7226" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Scrape Yandex Images Results Using Playwright and Browserless?]]></title>
            <link>https://medium.com/@pumpkingee/how-to-scrape-yandex-images-results-using-playwright-and-browserless-7b92d9bed28f?source=rss-de43916695e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b92d9bed28f</guid>
            <category><![CDATA[browserless]]></category>
            <category><![CDATA[yandex]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Parker Montgomery]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 10:10:00 GMT</pubDate>
            <atom:updated>2024-10-24T10:10:00.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NR-aNg3WpWpksKGf" /></figure><h3>What Is Yandex?</h3><p>Yandex is a multinational company based in Russia that is best known for its search engine, which is among the biggest in the country. Yandex provides a range of services in addition to search capabilities. Additionally, Yandex provides Yandex Image Search, which allows you to look for photographs using keywords.</p><p>The results of Yandex image searches differ slightly from those of Google and Bing. Numerous filters, including size, orientation, type, color, format, recent, and wallpaper, are also supported by Yandex image search.</p><p>Thousands of photos can be scraped for a variety of purposes, including marketing, branding, research, teaching, and creative.</p><h3>Scraping Yandex Is Really Difficult!</h3><p>Yandex employs advanced anti-bot measures designed to detect and block automated requests. This includes the implementation of CAPTCHAs and strict IP rate limiting, which can hinder scraping efforts.</p><p>Many Yandex pages feature dynamic content that loads via JavaScript. This means that simple scraping techniques may not capture all relevant information, necessitating the use of more sophisticated tools such as headless browsers.</p><p>Additionally, Yandex frequently updates its algorithms and the structure of its pages. This constant evolution can cause scraping scripts to break, requiring regular maintenance and adjustments.</p><p>There are legal considerations to take into account, as scraping may violate Yandex’s terms of service, potentially leading to legal repercussions for users.</p><p>The vast amount of data available on Yandex means that efficient data handling is essential, adding another layer of complexity to the scraping process.</p><p>These factors combined make scraping Yandex a challenging endeavor that requires careful planning and execution.</p><h3>Why Browserless Works Well for Scraping Yandex Image Search?</h3><p>Nstbrowser’s Browserless is a typical Headless Chrome cloud service that operates online applications and automates scripts without a graphical user interface. For tasks like web scraping and other automated operations, it is especially helpful.</p><p><strong>Nstbrowser integrates anti-detection, web unblocker, and browserless features into Browserless.</strong> <strong>Browserless is totally free to test.</strong></p><blockquote><em>Do you have any wonderful ideas or doubts about web scraping and Browserless?<br>Let’s see what other developers are sharing on </em><a href="https://discord.com/invite/7Bgefnycx6"><strong><em>Discord</em></strong></a><em>!</em></blockquote><h3>How to Scrape Yandex Image Search Results?</h3><h3>Environment Preset</h3><p>At the very beginning, we should prepare our Browserless service. Browserless can help solve complex web crawling and large-scale automation tasks, and fully managed cloud deployment has been achieved.</p><ol><li>Browserless uses a browser-centric approach, offers robust headless deployment features, and provides improved dependability and speed. Check out the <a href="https://apidocs.nstbrowser.io/doc-639323">documentation on Browserless</a> for additional details.</li><li>Go to the Browserless menu page of the Nstbrowser client to obtain the API KEY.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XMxQjDWiRVY9i785.png" /></figure><h3>Determine the crawling target</h3><p>Just as before, please follow us to determine the scraping target first.</p><p>Let’s use Playwright and combine it with Nstbrowser&#39;s Browserless service to crawl the top images when searching for the keyword &quot;<strong>cat</strong>&quot;.</p><p>The data we need includes: “<strong>image address</strong>”, “<strong>image summary</strong>”, “<strong>image width</strong>”, and “<strong>image height</strong>”, and save the results to a CSV file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N-AXz6OjF1zQ6WRx.png" /></figure><h3>Start crawling using Nstbrowser Browserless service</h3><p>Follow the steps below to create the project and start scraping:</p><h4>Step 1. Build a main.py file and a new Python project.</h4><h4>Step 2. Using Nstbrowser’s Browserless to create a browser instance.</h4><pre>from playwright.sync_api import sync_playwright<br><br>token = &quot;You API token&quot; # required<br>config = {<br>    &quot;proxy&quot;: &quot;&quot;, # required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080<br>    # &quot;platform&quot;: &quot;windows&quot;,  # support: windows, mac, linux<br>    # &quot;kernel&quot;: &quot;chromium&quot;,  # only support: chromium<br>    # &quot;kernelMilestone&quot;: &quot;124&quot;,  # support: 113, 120, 124<br>    # &quot;args&quot;: {<br>    #     &quot;--proxy-bypass-list&quot;: &quot;detect.nstbrowser.io&quot;<br>    # },  # browser args<br>    # &quot;fingerprint&quot;: {<br>    #     &quot;userAgent&quot;: &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36&quot;,<br>    # },<br>}<br><br>query = urlencode({<br>    &quot;token&quot;: token,<br>    &quot;config&quot;: json.dumps(config)<br>})<br><br>browser_ws_endpoint = f&quot;ws://less.nstbrowser.io/connect?{query}&quot;<br><br>def get_browser():<br>    playwright = sync_playwright().start()<br>    return playwright.chromium.connect_over_cdp(browser_ws_endpoint)</pre><h4>Step 3. Obtain image data and clean it</h4><ul><li>Define the crawl target website address:</li></ul><pre>target_website_url = &quot;https://yandex.com/images/search?family=yes&amp;from=tabbar&amp;text=cats&quot;</pre><ul><li>Here, Playwright uses the page.goto method to help open the target web page.</li></ul><p>This step is to ensure that the browser can load the page correctly and wait for the DOM content of the web page to be fully loaded.</p><pre>page.goto(url, timeout=60000, wait_until=&quot;domcontentloaded&quot;)</pre><ul><li>Next, we need to find all elements with data-state attributes on the page and try to find the target element (the element containing the image data).</li></ul><p>This step uses the query_selector_all method to get these elements and locate the element containing the image information through get_attribute(&quot;id&quot;) and get_attribute(&quot;data-state&quot;).</p><pre>data_states = page.query_selector_all(&quot;[data-state]&quot;)<br>images_app = None<br>for data_state in data_states:<br>    if &quot;ImagesApp&quot; in data_state.get_attribute(&quot;id&quot;):<br>        images_app = data_state.get_attribute(&quot;data-state&quot;)<br>        break</pre><ul><li>After getting the target element, the code calls the get_image_results function.</li></ul><p>This function parses the JSON data in the data-state attribute of the target element and extracts the image information.</p><pre>def get_image_results(images_app):<br>    images_app_obj = json.loads(images_app)<br>    images_lists = images_app_obj[&#39;initialState&#39;][&quot;serpList&quot;][&quot;items&quot;][&quot;entities&quot;]<br>    imgs = []<br>    for key in images_lists:<br>        img = images_lists[key]<br>        imgs.append({<br>            &quot;url&quot;: img[&quot;url&quot;],<br>            &quot;alt&quot;: img[&quot;alt&quot;],<br>            &quot;width&quot;: img[&quot;width&quot;],<br>            &quot;height&quot;: img[&quot;height&quot;],<br>        })<br><br>    return imgs</pre><h4>Step 4. Save the crawling results and export them to a CSV file</h4><p>Before saving the data, you need to define the header of the CSV file. Four fields are defined here: URL, Alt, Width, and Height. These fields represent the basic properties of each image. Use the open() function to open a file named yandex_images.csv in write mode (&#39;w&#39;). At the same time, the encoding format is specified as UTF-8 and newline=&#39;&#39; is set to avoid blank lines when writing.</p><pre>def save_csv(data):<br>    try:<br>        header = [&quot;URL&quot;, &quot;Alt&quot;, &quot;Width&quot;, &quot;Height&quot;]<br>        with open(&#39;yandex_images.csv&#39;, &#39;w&#39;, encoding=&#39;UTF8&#39;, newline=&#39;&#39;) as f:<br>            writer = csv.writer(f)<br>            writer.writerow(header)<br>            for item in data:<br>                writer.writerow(<br>                    [<br>                        item[&quot;url&quot;],<br>                        item[&quot;alt&quot;],<br>                        item[&quot;width&quot;],<br>                        item[&quot;height&quot;],<br>                    ])<br>        print(&quot;Saved to yandex_images.csv&quot;)<br>    except Exception as e:<br>        print(e)</pre><h4>The whole code lines</h4><pre>import json<br>import csv<br>from urllib.parse import urlencode<br><br>from playwright.sync_api import sync_playwright<br><br>token = &quot;&quot;  # required<br>config = {<br>    &quot;proxy&quot;: &quot;&quot;, # required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080<br>    # &quot;platform&quot;: &quot;windows&quot;,  # support: windows, mac, linux<br>    # &quot;kernel&quot;: &quot;chromium&quot;,  # only support: chromium<br>    # &quot;kernelMilestone&quot;: &quot;124&quot;,  # support: 113, 120, 124<br>    # &quot;args&quot;: {<br>    #     &quot;--proxy-bypass-list&quot;: &quot;detect.nstbrowser.io&quot;<br>    # },  # browser args<br>    # &quot;fingerprint&quot;: {<br>    #     &quot;userAgent&quot;: &quot;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36&quot;,<br>    # },<br>}<br><br>query = urlencode({<br>    &quot;token&quot;: token,<br>    &quot;config&quot;: json.dumps(config)<br>})<br><br>browser_ws_endpoint = f&quot;ws://less.nstbrowser.io/connect?{query}&quot;<br>target_website_url = &quot;https://yandex.com/images/search?family=yes&amp;from=tabbar&amp;text=cats&quot;<br><br><br>def get_browser():<br>    playwright = sync_playwright().start()<br>    return playwright.chromium.connect_over_cdp(browser_ws_endpoint)<br><br><br>def get_image_results(images_app):<br>    try:<br>        images_app_obj = json.loads(images_app)<br>        images_lists = images_app_obj[&#39;initialState&#39;][&quot;serpList&quot;][&quot;items&quot;][&quot;entities&quot;]<br>        imgs = []<br>        for key in images_lists:<br>            img = images_lists[key]<br>            imgs.append({<br>                &quot;url&quot;: img[&quot;url&quot;],<br>                &quot;alt&quot;: img[&quot;alt&quot;],<br>                &quot;width&quot;: img[&quot;width&quot;],<br>                &quot;height&quot;: img[&quot;height&quot;],<br>            })<br><br>        return imgs<br><br>    except Exception as e:<br>        print(e)<br><br><br>def get_tar(url, page):<br>    try:<br>        print(&quot;Open page: &quot; + url)<br>        page.goto(url, timeout=60000, wait_until=&quot;domcontentloaded&quot;)<br>        data_states = page.query_selector_all(&quot;[data-state]&quot;)<br>        images_app = None<br>        results = []<br>        for data_state in data_states:<br>            if &quot;ImagesApp&quot; in data_state.get_attribute(&quot;id&quot;):<br>                images_app = data_state.get_attribute(&quot;data-state&quot;)<br>                break<br><br>        if images_app is None:<br>            print(&quot;Cannot find the target element&quot;)<br>        else:<br>            print(&quot;Found the target element&quot;)<br>            results = get_image_results(images_app)<br><br>        return results<br>    except Exception as e:<br>        print(e)<br><br><br>def save_csv(data):<br>    try:<br>        header = [&quot;URL&quot;, &quot;Alt&quot;, &quot;Width&quot;, &quot;Height&quot;]<br>        with open(&#39;yandex_images.csv&#39;, &#39;w&#39;, encoding=&#39;UTF8&#39;, newline=&#39;&#39;) as f:<br>            writer = csv.writer(f)<br>            writer.writerow(header)<br>            for item in data:<br>                writer.writerow(<br>                    [<br>                        item[&quot;url&quot;],<br>                        item[&quot;alt&quot;],<br>                        item[&quot;width&quot;],<br>                        item[&quot;height&quot;],<br>                    ])<br>        print(&quot;Saved to yandex_images.csv&quot;)<br>    except Exception as e:<br>        print(e)<br><br><br>def main():<br>    try:<br>        with get_browser() as browser:<br>            page = browser.new_page()<br>            res = get_tar(target_website_url, page)<br>            if len(res) == 0:<br>                print(&quot;No results&quot;)<br>            else:<br>                save_csv(res)<br>            browser.close()<br>    except Exception as e:<br>        print(e)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>Scraping result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lBMYO3qRdN5Qf9P2.png" /></figure><h3>It’s A Wrap</h3><p>Scraping Yandex image search is difficult, as everyone knows. However, you can easily scrape Yandex search results for any chosen term and export the data into CSV or JSON files if you follow the scraping instructions in this post and utilize the Python code that is provided.</p><p>You can easily scrape Yandex SERP at scale with <a href="https://www.nstbrowser.io/en/product/browserless"><strong>Browserless</strong></a>. Now, using Browserless is totally free. Don’t pass up this fantastic chance!</p><blockquote><strong><em>Disclaimer</em></strong><em>: Any data and websites mentioned in this article are for demonstration purposes only. We firmly oppose illegal and infringing activities. If you have any questions or concerns, please contact us promptly.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b92d9bed28f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Scrape Dynamic Websites Using Browserless?]]></title>
            <link>https://medium.com/@pumpkingee/how-to-scrape-dynamic-websites-using-browserless-4d212ec80e86?source=rss-de43916695e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d212ec80e86</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[browserless]]></category>
            <dc:creator><![CDATA[Parker Montgomery]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 09:02:53 GMT</pubDate>
            <atom:updated>2024-10-18T09:02:53.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C_11ROi7zT0xKZF_" /></figure><h3>What Is a Dynamic Web Page?</h3><p>A dynamic web page is one where the content is not all directly embedded in static HTML but is generated through server-side or client-side rendering.</p><p>It can display data in real time based on user actions, such as loading more content when the user clicks a button or scrolls down the page (such as infinite scrolling). This design improves the user experience and allows users to get relevant information without reloading the entire page.</p><p>To determine whether a website is a dynamic web page, you can disable JavaScript in your browser. If the website is dynamic, most of the content will disappear.</p><h3>Challenges when Scraping Dynamic Websites</h3><h3>Fingerprinting and Blocking</h3><ol><li><strong>Fingerprinting techniques</strong>: Many websites use fingerprinting techniques to detect and block automated scrapers. These techniques create a unique “fingerprint” for each visitor by analyzing information such as browser behavior, screen resolution, plugins, time zone, etc. If anomalies are detected or inconsistent with regular user behavior, the website may block access.</li><li><strong>Blocking mechanisms</strong>: To protect their content, websites implement various blocking mechanisms, such as:</li></ol><ul><li><strong>IP blocking</strong>: When frequent requests come from the same IP address, the website may temporarily or permanently ban access from that IP address.</li><li><strong>CAPTCHA verification</strong>: Websites may introduce CAPTCHA when automated traffic is detected to confirm that the visitor is human.</li><li><strong>Traffic limiting</strong>: Set a request rate limit, and when the request rate exceeds the preset threshold, the website will reject further requests.</li></ul><h3>Local loading challenges</h3><ol><li><strong>Resource consumption</strong>: Dynamic pages usually require more system resources for rendering and data crawling. When using tools like Puppeteer or Selenium, it may cause high memory and CPU usage, especially when crawling multiple pages.</li><li><strong>Latency and time cost</strong>: Due to the need to wait for the page to be fully loaded (including JavaScript execution and AJAX requests), the time cost of crawling dynamic pages may be high, which will affect the efficiency of the entire crawler.</li><li><strong>Concurrent processing</strong>: Under high load conditions, processing multiple crawling tasks at the same time may cause system overload, resulting in request failure or timeout. This requires reasonable task scheduling and resource management strategies.</li></ol><blockquote><em>Do you have any wonderful ideas or doubts about web scraping and Browserless?<br>Let’s see what other developers are sharing on </em><a href="https://discord.com/invite/7Bgefnycx6"><strong><em>Discord</em></strong></a><em> and </em><a href="https://t.me/+GTaFK2QAz605Mzg1"><strong><em>Telegram</em></strong></a><em>!</em></blockquote><h3>6 Effective Ways for Scraping Dynamic Websites</h3><h3>1. Intercept XHR/Fetch requests</h3><p>An effective method to intercept XHR (XMLHttpRequest) and Fetch requests during the scraping process is to inspect the browser’s Network tab to identify API endpoints that provide dynamic content. Once these endpoints are identified, HTTP clients such as the Requests library can be used to send requests directly to these APIs to obtain data.</p><ul><li><strong>Pros</strong>: This method is generally fast and can extract data efficiently because it only fetches the required content instead of the entire web page.</li><li><strong>Cons</strong>: This can be challenging if the data is stored in the DOM as JSON instead of being returned by the API. In addition, the process of simulating API requests can be affected by API changes, rate limits, and authentication requirements, resulting in poor scalability.</li></ul><h3>2. Use a headless browser</h3><p>Using a headless browser like Puppeteer or Selenium allows full simulation of user behavior, including page loading and interaction. These tools are able to process JavaScript and scrape dynamically generated content.</p><ul><li><strong>Pros</strong>: This method is able to scrape highly dynamic websites and support complex user interactions.</li><li><strong>Cons</strong>: high resource consumption, slow crawling speed, and may need to deal with complex page structures and dynamic content.</li></ul><h3>3. API request</h3><p>Requesting data directly from the website’s API is an efficient way to crawl. Analyze the website’s network requests, find the API endpoint, and use the HTTP client to request data.</p><ul><li><strong>Pros</strong>: Ability to directly obtain the required data and avoid the complexity of parsing HTML.</li><li><strong>Cons</strong>: If the API requires authentication or has a request frequency limit, it may affect crawling efficiency.</li></ul><h3>4. Crawl AJAX requests</h3><p>By monitoring network requests, identifying AJAX calls, and reproducing them, dynamically loaded data can be extracted.</p><ul><li><strong>Pros</strong>: Directly obtain data sources and reduce unnecessary loading.</li><li><strong>Cons</strong>: Need to have a certain understanding of the parameters and format of AJAX requests, and may also face authentication and rate limit issues.</li></ul><h3>5. Proxy and IP rotation</h3><p>In order to avoid being blocked by the website, using proxy services and IP rotation is an important strategy. This can help disperse requests and reduce the risk of detection.</p><ul><li><strong>Pros</strong>: Reduce the probability of being blocked and can maintain effectiveness in a large number of requests.</li><li><strong>Cons</strong>: Using proxy services may increase crawling costs and require maintaining a proxy list.</li></ul><h3>6. Simulate user behavior</h3><p>Writing scripts to simulate human browsing behavior, such as adding delays between requests, randomizing the order of operations, etc., can help reduce the risk of being identified as a crawler by the website.</p><ul><li><strong>Pros</strong>: Data crawling can be performed more naturally, reducing the risk of being detected.</li><li><strong>Cons</strong>: The implementation is relatively complex, and it takes time to adjust and optimize the simulated behavior.</li></ul><h3>What Is Browserless?</h3><p>Browserless is a headlesschrome cloud service that operates online applications and automates scripts without a graphical user interface. For jobs like web scraping and other automated operations, it is especially helpful.</p><blockquote><a href="https://www.youtube.com/watch?v=DTMnewNki-0"><strong>Find more details in our video!</strong></a></blockquote><h3>Browserless Makes Scraping Dynamic Web Pages Easily</h3><p>Browserless is also a powerful headless browser. Next, we will use Browserless as an example to crawl dynamic web pages.</p><h3>Prerequisite</h3><p>Before we start, we need to have a Browserless service. Using Browserless can solve complex web crawling and large-scale automation tasks, and now fully managed cloud deployment has been achieved.</p><p>Browserless adopts a browser-centric strategy, provides powerful headless deployment capabilities, and provides higher performance and reliability. You can learn more about the configuration of Browserless services from the documentation.</p><p>At the very beginning, we needed to get the API KEY of Nstbrowser. You can go to the Browserless menu page of the Nstbrowser client, or you can visit the Browserless panel in the Nstbrowser client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aERTJv7b42b_CDi_.png" /></figure><h3>Determine the crawling target</h3><p>Before we start, let’s determine the goal of this test. We will use Puppeteer and Playwright to get the page title content of dynamic websites:</p><ol><li>Visit the target website: <a href="https://www.nstbrowser.io/en">https://www.nstbrowser.io/en</a></li><li>Get the dynamic page title content</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6OEMETcFI8DnEV8Y.png" /></figure><h3>Initialize the project</h3><p>Follow the steps below to install dependencies:</p><ul><li><strong>Step 1</strong>: Create a new folder in Vs code</li><li><strong>Step 2</strong>: Open the Vs code terminal and run the following commands to install related dependencies</li></ul><pre>npm init -y<br>pnpm add playwright puppeteer-core</pre><h3>Scrape dynamic web pages using Playwright and Browserless</h3><ul><li>Create a crawling script</li></ul><pre>const { chromium } = require(&#39;playwright&#39;);<br><br>async function createBrowser() {<br>  const token = &#39;&#39;; // required<br>  const config = {<br>    proxy:<br>      &#39;&#39;, // required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080<br>    // platform: &#39;windows&#39;, // support: windows, mac, linux<br>    // kernel: &#39;chromium&#39;, // only support: chromium<br>    // kernelMilestone: &#39;124&#39;, // support: 113, 120, 124<br>    // args: {<br>    //   &#39;--proxy-bypass-list&#39;: &#39;detect.nstbrowser.io&#39;,<br>    // }, // browser args<br>    // fingerprint: {<br>    //   userAgent:<br>    //     &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36&#39;,<br>    // },<br>  };<br>  const query = new URLSearchParams({<br>    token: token, // required<br>    config: JSON.stringify(config),<br>  });<br><br>  const browserWSEndpoint = `ws://less.nstbrowser.io/connect?${query.toString()}`;<br>  const browser = await chromium.connectOverCDP(browserWSEndpoint);<br>  const context = await browser.newContext();<br>  const page = await context.newPage();<br><br>  page.goto(&#39;https://www.nstbrowser.io/en&#39;);<br><br>  // sleep for 5 seconds<br>  await new Promise((resolve) =&gt; setTimeout(resolve, 5000));<br><br>  const h1Element = await page.$(&#39;h1&#39;);<br>  const content = await h1Element?.textContent();<br>  console.log(`Playwright: The content of the h1 element is: ${content}`)<br><br>  await page.close();<br>  await page.context().close();<br>}<br><br>createBrowser().then();</pre><ul><li>Check the scraping result</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/0*R1_shCqGvU4STG67.png" /></figure><h3>Scrape dynamic web pages using Puppeteer and Browserless</h3><ul><li>Create a crawling script</li></ul><pre>const puppeteer = require(&#39;puppeteer-core&#39;);<br><br>async function createBrowser() {<br>  const token = &#39;&#39;; // required<br>  const config = {<br>    proxy:<br>      &#39;&#39;, // required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080<br>    // platform: &#39;windows&#39;, // support: windows, mac, linux<br>    // kernel: &#39;chromium&#39;, // only support: chromium<br>    // kernelMilestone: &#39;124&#39;, // support: 113, 120, 124<br>    // args: {<br>    //   &#39;--proxy-bypass-list&#39;: &#39;detect.nstbrowser.io&#39;,<br>    // }, // browser args<br>    // fingerprint: {<br>    //   userAgent:<br>    //     &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36&#39;,<br>    // },<br>  };<br>  const query = new URLSearchParams({<br>    token: token, // required<br>    config: JSON.stringify(config),<br>  });<br><br>  const browserWSEndpoint = `ws://less.nstbrowser.io/connect?${query.toString()}`;<br>  const browser = await puppeteer.connect({<br>    browserWSEndpoint: browserWSEndpoint,<br>    defaultViewport: null,<br>  });<br>  const page = await browser.newPage();<br><br>  await page.goto(&#39;https://www.nstbrowser.io/en&#39;);<br><br>  // sleep for 5 seconds<br>  await new Promise((resolve) =&gt; setTimeout(resolve, 5000));<br><br>  const h1Element = await page.$(&#39;h1&#39;);<br><br>  if (h1Element) {<br>    const content = await page.evaluate((el) =&gt; el.textContent, h1Element); // use page.evaluate to get the text content of the h1 element<br>    console.log(`Puppeteer: The content of the h1 element is: ${content}`);<br>  } else {<br>    console.log(&#39;No h1 element found.&#39;);<br>  }<br><br>  await page.close();<br>}<br><br>createBrowser().then();</pre><ul><li>Check the scraping result</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*ADpRVBTfK0XIl3k0.png" /></figure><h3>Conclusion</h3><p>Crawling dynamic web pages is always more complicated than crawling ordinary web pages. It is easy to encounter various troubles during the crawling process. Through the introduction of this blog, you must have learned:</p><ul><li>6 effective ways to crawl dynamic web pages</li><li>Use <a href="https://apidocs.nstbrowser.io/folder-1444256?nav=1">Browserless</a> to easily crawl dynamic web pages</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d212ec80e86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Run Parallel Tests in Puppeteer using Browserless?]]></title>
            <link>https://medium.com/@pumpkingee/how-to-run-parallel-tests-in-puppeteer-using-browserless-5bde4b2cf5d4?source=rss-de43916695e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bde4b2cf5d4</guid>
            <category><![CDATA[browserless]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <dc:creator><![CDATA[Parker Montgomery]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 11:05:35 GMT</pubDate>
            <atom:updated>2024-10-15T11:05:35.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NPF-TUUx8pcba3lW" /></figure><h3>What Is Parallel Testing?</h3><p>What is parallelization?</p><p>Parallel testing is also named parallel execution. In parallel testing, we test different modules or applications on multiple browsers in parallel instead of testing them one by one.</p><p>Parallelization is different from sequential testing, where we test different modules or functionalities one after another. Even when testing an application on multiple browsers, the tests are executed sequentially on each browser. This testing method is very time-consuming.</p><p>Parallel execution helps reduce execution time and effort, thereby reducing delivery time. It proves to be particularly useful in cross-browser testing, compatibility testing, localization, and internalization testing. In situations where we have two versions of the software available and need to check their stability and compatibility, we can run both versions simultaneously and find issues at a faster pace.</p><h3>Parallelization vs. Serialization — Which is better?</h3><h3>1. Parallelization</h3><p>Parallelization means running multiple tasks at the same time, which can often significantly improve speed, especially when testing or executing tasks.</p><h4>Pros:</h4><ul><li><strong>Faster</strong>: Parallelization allows multiple tasks to proceed at the same time, reducing the overall running time. Tasks that can run concurrently can significantly improve efficiency.</li><li><strong>Make full use of resources</strong>: Parallelization can maximize the advantages of multi-core CPUs and multi-threaded environments and is particularly suitable for multitasking and situations where a large number of I/O operations need to be processed (such as network requests, page loading, etc.).</li><li><strong>Suitable for large-scale testing</strong>: For large test suites, multiple test scenarios can be completed quickly through parallel execution.</li></ul><h4>Cons:</h4><ul><li><strong>High resource consumption</strong>: Parallelization will occupy more system resources (such as CPU, and memory). When too many browser instances or pages are launched, it may cause system resource exhaustion or performance degradation.</li><li><strong>Increased complexity</strong>: Managing the results, synchronization, and error handling of parallel tasks becomes more complicated. Shared resources in tests (such as databases, and file systems) require special attention to prevent race conditions or conflicts.</li><li><strong>Not suitable for tasks that depend on order</strong>: If there are dependencies between tasks (for example, task A must be completed before task B), parallelization may cause problems.</li></ul><h4>Applicable scenarios:</h4><ul><li>Scenarios where there are a large number of independent tasks or tests that can be executed simultaneously.</li><li>There are powerful hardware resources to support concurrent operations.</li><li>Need to complete large-scale tasks quickly.</li></ul><h3>2. Serialization</h3><p>Serialization means that tasks are executed one after another in order until all tasks are completed.</p><h4>Pros:</h4><ul><li><strong>Low resource requirements</strong>: Since only one task is run at a time, resource usage is relatively low, system stability is higher, and resource competition and exhaustion are avoided.</li><li><strong>Easy to manage</strong>: The order of tasks is clear, and debugging and error handling are relatively simple. Especially when there are dependencies between tasks, serialization can ensure that tasks are executed in the expected order.</li><li><strong>Suitable for dependent tasks</strong>: When tasks have a sequence or dependency, serialized execution avoids race conditions.</li></ul><h4>Cons:</h4><ul><li><strong>Slower speed</strong>: Because only one task is executed at a time, the multi-core processing power of the system cannot be utilized, and the overall execution time will be longer than parallelization.</li><li><strong>Waste of resources</strong>: Even if there are more available resources, serialization still only uses a part of the resources, resulting in insufficient hardware performance.</li></ul><h4>Applicable scenarios:</h4><ul><li>There are dependencies between tasks and they must be completed in sequence.</li><li>Limited system resources or parallelization may lead to performance degradation.</li><li>Task complexity is high and the error rate is high, so you need to troubleshoot the problem step by step.</li></ul><h3>In short</h3><ul><li>If you pursue speed and there is no dependency between tasks, parallelization is better and can improve efficiency.</li><li>If there is a dependency between tasks or system resources are limited, serialization is more secure, although the speed may be slower.</li></ul><h3>Run Parallel execution in Puppeteer using Browserless</h3><h3>Step1: Get the API Key</h3><p>Before getting started, it’s necessary to have a Browserless service. Browserless can solve complex web crawling and large-scale automation tasks, and it has now achieved fully managed cloud deployment.</p><p>Browserless adopts a browser-centric approach, provides powerful headless deployment capabilities, and provides higher performance and reliability. For more information about Browserless, you can go to read our document to learn more.</p><ol><li>Get the API KEY and go to the Browserless menu page of the Nstbrowser client, or you can go to check the Browserless to access:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*89UxC56JYr604gvm.png" /></figure><h3>Step2: Install puppeteer-cluster-connect</h3><p>Why use Puppeteer?</p><p><strong>Puppeteer</strong> has many maintainers and is very active. It is also built by Chrome developers, so it is one of the highest-quality libraries. So next, we will use Puppeteer to connect Browserless for parallel testing.</p><p>Puppeteer-cluster can create multiple puppeteer workers. This library generates a pool of Chromium instances through Puppeteer and helps track operations and errors. It can help us do parallel testing well, but this library does not yet support puppeteer.connect, so it cannot connect to external browser ports.</p><p>So in the following examples, we will use <strong>puppeteer-cluster-connect</strong> instead:</p><pre>npm install --save puppeteer<br>npm install --save puppeteer-cluster-connect</pre><h3>Step3: Use puppeteer-cluster-connect to connect to Browserless</h3><p>We need to prepare the following function. Just fill in your api key and proxy to start connecting to Browserless:</p><pre>async function getBrowserWSEndpoint() {<br>  const token = &quot;your api key&quot;; // &#39;your proxy&#39;<br>  const config = {<br>    proxy: &#39;your proxy&#39;, // required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080<br>    // platform: &#39;windows&#39;, // support: windows, mac, linux<br>    // kernel: &#39;chromium&#39;, // only support: chromium<br>    // kernelMilestone: &#39;128&#39;, // support: 128<br>    // args: {<br>    //     &quot;--proxy-bypass-list&quot;: &quot;detect.nstbrowser.io&quot;<br>    // }, // browser args<br>    // fingerprint: {<br>    //     userAgent: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36&#39;, // userAgent supportted since v0.15.0<br>    // },<br>  };<br><br>  const query = new URLSearchParams({<br>    token: token, // required<br>    config: JSON.stringify(config),<br>  });<br><br>  return `https://less.nstbrowser.io/connect?${query.toString()}`;<br>}</pre><p>Next, we need to use the connecting method of puppeteer-cluster-connect to connect to Browserless;</p><ul><li>Concurrency is the implementation type of concurrency. Here we set Cluster.CONCURRENCY_CONTEXT, which means that each URL will create an invisible page (BrowserContext) that does not share data;</li><li>MaxConcurrency is the maximum number of concurrencies.</li><li>RestartFunction is the method for restarting the port when it crashes.</li></ul><p>At this point, our Browserless cluster is ready!</p><pre>import puppeteer from &quot;puppeteer-core&quot;;<br>import { Cluster } from &quot;puppeteer-cluster-connect&quot;<br><br>const cluster = await Cluster.connect({<br>  concurrency: Cluster.CONCURRENCY_CONTEXT,<br>  maxConcurrency: 3,<br>  // provide the puppeteer-core library<br>  puppeteer,<br>  puppeteerOptions: {<br>    browserWSEndpoint: await getBrowserWSEndpoint(),<br>    defaultViewport: null<br>  },<br>  // Put restart function callback here<br>  restartFunction: getBrowserWSEndpoint,<br>});<br><br>console.log(&#39;cluster is Connected!&#39;);</pre><h3>Step4: Start parallel testing</h3><p>Next, we will conduct a simple parallel test. We hope to quickly access multiple sites in batches in parallel, record the titles of these sites, and take screenshots after the page is loaded to test whether these sites can be accessed normally.</p><ul><li>Use the task method of the cluster obtained in the previous step to create a task. This task contains the operation function corresponding to each browser instance:</li></ul><pre>await cluster.task(async ({ page, data }) =&gt; {<br>  const { url, name } = data<br>  // Visit Target Site<br>  await page.goto(url);<br>  console.log(`[${name} page loaded]:`, url);<br>  // Get document title<br>  const documentTitle = await page.evaluate(() =&gt; document.title)<br>  console.log(`[${name} title]:`, documentTitle);<br>  // take a screenshot<br>  await page.screenshot({ fullPage: true, path: `${name}.png` });<br>});</pre><ul><li>The queue method should be used to add data that needs to be tested in parallel to the cluster</li><li>Then, please use idle and close methods to close the cluster and all open browser instances:</li></ul><pre>cluster.queue({ url: &quot;https://www.google.com&quot;, name: &#39;google&#39; });<br>cluster.queue({ url: &quot;https://www.wikipedia.org&quot;, name: &#39;wikipedia&#39; });<br>cluster.queue({ url: &quot;https://github.com/&quot;, name: &#39;github&#39; });<br><br>await cluster.idle();<br>await cluster.close();</pre><ul><li>Now, we can run the above script to see the results of the above parallel tests:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/0*dgd6i5toVCFbY8sl.png" /></figure><ul><li>You can also see the corresponding screenshots in the path where the script is executed:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/0*l7bRHQXtPrkEzTf8.png" /></figure><h3>Step5: Check the Browserless Dashboard</h3><p>You can view statistics for recent requests and remaining session time in the Browserless menu of the Nstbrowser client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-lZde36Yk_CNyglq.png" /></figure><h3>It’s a Wrap</h3><p>Do you always need to parallelize your work? Running tests in parallel always requires access to multiple platforms and browsers, which increases our testing costs.</p><p>In addition, we may encounter situations where we cannot access all browsers and versions. <a href="https://apidocs.nstbrowser.io/doc-639323?nav=1">Browserless</a> can easily help you solve the above problems. It only takes 4 simple steps to easily complete parallel testing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bde4b2cf5d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Headless Browser Testing: How to Do It Using Puppeteer and Browserless?]]></title>
            <link>https://medium.com/@pumpkingee/headless-browser-testing-how-to-do-it-using-puppeteer-and-browserless-c2a3b2a499a8?source=rss-de43916695e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2a3b2a499a8</guid>
            <category><![CDATA[browserless]]></category>
            <category><![CDATA[browser-testing]]></category>
            <category><![CDATA[puppeteer]]></category>
            <dc:creator><![CDATA[Parker Montgomery]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 07:51:30 GMT</pubDate>
            <atom:updated>2024-10-12T07:51:30.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kAINk7bElWnz5an3" /></figure><h3>What is Headless Browser Testing?</h3><p>Headless browser testing generally refers to an object or thing without a head, and in the context of a browser, it refers to a browser simulation without a UI. Headless browser automation uses a web browser for end-to-end testing without loading the browser’s UI.</p><ul><li>Headless mode is a feature that allows the execution of a full version of a browser while controlling it programmatically.</li><li>They are executed through a command line interface or using network communication. This means it can be used in a server without graphics or a display, and Selenium tests will still run!</li><li>When the web page is not rendered on the screen, and the tests are executed without UI interaction, the execution speed is faster than real browser automation.</li></ul><h3>Functions of Puppeteer</h3><p>Some of the main features of Puppeteer include:</p><ol><li><strong>Headless browsing</strong>: Puppeteer can control a headless version of Chrome or Chromium, which means that the browser can run without a graphical user interface (GUI). This enables it to perform background tasks and automation efficiently.</li><li><strong>Automated tasks</strong>: Puppeteer allows you to simulate user interactions, such as browsing pages, clicking buttons, filling out forms, etc. It can also automatically access web pages and extract data, which is suitable for data collection and analysis.</li><li><strong>Page manipulation</strong>: You can modify web page content by injecting JavaScript code, changing styles, and manipulating DOM (Document Object Model).</li><li><strong>Screenshot and PDF generation</strong>: Puppeteer can screenshot or export web pages to PDF format. This is very useful for creating visual reports and documents.</li><li><strong>Network monitoring</strong>: Puppeteer can intercept and modify network requests and responses for debugging or testing different network scenarios.</li><li><strong>Performance analysis</strong>: Get performance indicators such as page loading time and resource usage to help optimize web page performance.</li><li><strong>Web Scraping</strong>: Puppeteer is often used for web scraping tasks because it can interact with websites like real users, thus extracting data from dynamic and JavaScript-heavy pages.</li><li><strong>Testing</strong>: Puppeteer is often used to automate end-to-end testing of web applications. It can simulate user behavior and interactions to ensure that your web application runs as expected.</li><li><strong>Headless and Head Mode</strong>: It can be run in headless mode or debugged in head mode, which is convenient for development and testing.</li></ol><h3>What Does Headless Mean in the Puppeteer？</h3><p>Puppeteer is a Node.js library for controlling Chrome or Chromium browsers, primarily for tasks such as automated testing, web scraping, and generating PDFs. The “headless” in Puppeteer refers to a browser instance that can run without a user interface.</p><p>In other words, the browser runs in the background and does not display a window with which you can interact visually. Instead, it performs tasks programmatically and can be controlled by scripts or code.</p><p>Puppeteer allows you to control a regular browser instance with a visible GUI and a headless browser instance. Headless mode is particularly useful for tasks such as web scraping, automated testing, and generating screenshots or PDFs, as it allows these tasks to be performed efficiently without the browser window being displayed.</p><p>Some benefits of using Puppeteer headless mode:</p><ol><li><strong>Performance</strong>: Browsers in headless mode typically run faster than graphical browsers because they do not have to render and display the visual elements of a web page.</li><li><strong>Resource efficiency</strong>: Since no graphical user interface is displayed, headless browsers take up less memory and CPU resources than running a full browser with a GUI, making them suitable for running on a server or in a CI/CD environment.</li><li><strong>Background tasks</strong>: Headless browsers are well suited for automated tasks that do not require user interaction or visual feedback, such as web scraping and automated testing.</li><li><strong>Server-side operations</strong>: Headless browsers can be used in server environments to automate tasks without a physical display.</li><li><strong>Automation</strong>: Scripts can be written to simulate user browser operations such as clicks, input, screenshots, etc. without manual intervention.</li></ol><p>Headless browsers are particularly powerful for tasks that require automated interaction with websites, data extraction, testing, and other operations that do not require visual rendering.</p><blockquote><em>Do you have any wonderful ideas or doubts about web scraping and Browserless?<br>Let’s see what other developers are sharing on </em><a href="https://discord.com/invite/7Bgefnycx6"><strong><em>Discord</em></strong></a><em> and </em><a href="https://t.me/+GTaFK2QAz605Mzg1"><strong><em>Telegram</em></strong></a><em>!</em></blockquote><p>How to do headless browser testing with Puppeteer and Browserless?</p><p>Let’s figure it out in the following content!</p><h3>Running Headless Testing in Puppeteer with Browserless</h3><h3>Initialize the environment</h3><p>Before testing, we need to have a Browserless service. Browserless can help us solve complex web crawling and large-scale automation tasks. With cloud deployment of fully managed achievement, Browserless has a more powerful function.</p><p>Browserless adopts a browser-centric strategy, provides powerful headless deployment capabilities, and offers higher performance and reliability. Please <a href="https://apidocs.nstbrowser.io/doc-639323">click here</a> to learn more about the configuration of the Browserless service.</p><ul><li>We need to get the API KEY of Nstbrowser first. You can go to the Browserless menu page of the Nstbrowser client, or just <a href="https://app.nstbrowser.io/app/browserless">click here</a> to access:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YDXYAhC7lou_uHZl.png" /></figure><h3>Determine the test case target</h3><p>After completing the environment initialization, we need to further determine the target of our test.</p><blockquote><em>We will just learn an example of how to use Puppeteer with Browserless without specific web pages. </em><strong><em>Please specify the sample to your target websites and requirements</em></strong><em>.</em></blockquote><p>Here, let’s use Puppeteer to get the title of the page and create a screenshot. After that, we will combine it with Jest to write test cases.</p><p>The following are our main test contents:</p><ol><li>Whether the title of the page is the target title</li><li>Whether the screenshot contains the target element</li></ol><h3>Project initialization</h3><p>Next, please follow the steps below to install Puppeteer and run the test script:</p><p><strong>Step 1</strong>: Create a new folder in Vs code</p><p><strong>Step 2</strong>: Open the Vs code terminal and run the following commands to install related dependencies</p><pre>npm init -y<br>pnpm add jest jest-html-reporter puppeteer-core</pre><p><strong>Step 3</strong>: Finish related files</p><ol><li>Create the jest.config.js configuration file to perform the related configuration:</li></ol><pre>module.exports = {<br>  testTimeout: 10000, // 10 seconds<br>  reporters: [<br>    &#39;default&#39;,<br>    [<br>      &#39;jest-html-reporter&#39;,<br>      {<br>        pageTitle: &#39;Test Report&#39;,<br>        outputPath: &#39;./test-report.html&#39;,<br>        includeFailureMsg: true,<br>        includeConsoleLog: true,<br>      },<br>    ],<br>  ],<br>};</pre><p>2. Create the __tests__/puppeteer.spec.js test script</p><blockquote><em>To launch the browser, you need to pass in the relevant configuration (for complete configuration, refer to </em><a href="https://apidocs.nstbrowser.io/endpoint-5418530"><em>LaunchNewBrowser</em></a></blockquote><pre>const puppeteer = require(&#39;puppeteer-core&#39;);<br><br>describe(&#39;My First Puppeteer Test&#39;, () =&gt; {<br>  it(&#39;should load the page and check the title&#39;, async () =&gt; {<br>    const browserWSEndpoint = await launchAndConnectToBrowser();<br>    const browser = await puppeteer.connect({<br>      browserWSEndpoint: browserWSEndpoint,<br>      defaultViewport: null,<br>    });<br>    const page = await browser.newPage();<br>    await page.goto(&#39;https://example.com&#39;);<br><br>    const title = await page.title();<br>    expect(title).toBe(&#39;Example Domain&#39;);<br><br>    await browser.close();<br>  });<br><br>  // take a screenshot of the page<br>  it(&#39;should take a screenshot of the page&#39;, async () =&gt; {<br>    const browserWSEndpoint = await launchAndConnectToBrowser();<br>    const browser = await puppeteer.connect({<br>      browserWSEndpoint: browserWSEndpoint,<br>      defaultViewport: null,<br>    });<br>    const page = await browser.newPage();<br>    await page.goto(&#39;https://example.com&#39;);<br><br>    await page.screenshot({ path: &#39;example.png&#39; });<br><br>    await browser.close();<br>  });<br>});<br><br>async function launchAndConnectToBrowser() {<br>  const token = &#39;&#39;; // your api token from nstbrowser<br>  const config = {<br>    proxy:<br>      &#39;&#39;, // required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080<br>    // platform: &#39;windows&#39;, // support: windows, mac, linux<br>    // kernel: &#39;chromium&#39;, // only support: chromium<br>    // kernelMilestone: &#39;128&#39;, // support: 128<br>    // args: {<br>    //     &quot;--proxy-bypass-list&quot;: &quot;detect.nstbrowser.io&quot;<br>    // }, // browser args<br>    // fingerprint: {<br>    //     userAgent: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36&#39;, // userAgent supportted since v0.15.0<br>    // },<br>  };<br>  const query = new URLSearchParams({<br>    token: token, // required<br>    config: JSON.stringify(config),<br>  });<br><br>  const browserWSEndpoint = `ws://less.nstbrowser.io/connect?${query.toString()}`;<br>  return browserWSEndpoint;<br>}</pre><h3>Run the project</h3><p>Now we just need to open the console and run the following script command:</p><pre>npx jest --detectOpenHandles</pre><p>The commands here can be mainly broken down into:</p><ul><li>Use the npx command to execute the jest command.</li><li>The jest will find the jest.config.js configuration file of the current project and obtain basic configuration information.</li><li>According to the content of the configuration file, find the matching test file in the current project directory and start executing.</li></ul><h3>Result output</h3><p>After executing the above command, we will see the following output. Here, each important result of the test execution process will be output, and it shows us that <strong>our test case has passed</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*ccWJLsC8nzKGbEnT.png" /></figure><p>At the same time, we can open the test-report.html file to view the specific report generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ayadn9FhAyiuu3nf.png" /></figure><p>The file structure of the project is as follows. We can also see the output screenshot file content, which means that our test case has been completely passed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/0*2K9LWlViSqhfe_Dl.png" /></figure><h3>Benefits of Puppeteer Headless Testing</h3><ol><li>Headless browser testing is faster compared to real browsers as it consumes fewer system resources.</li><li>It improves test execution performance as it usually executes 2 times faster than real browser testing.</li><li>It is perfect for web scraping. Suppose you need to fetch a lot of data (sports data, stock data, etc.) from a web page through Puppeteer automation and store it in any Excel or database. In this case, Puppeteer headless mode is best as there is no need to launch a real browser to verify the UI and the main focus is on fetching data.</li><li>It helps in emulating multiple browsers on a single system without resource overhead.</li><li>It is suitable for parallel testing. UI-based browsers consume a lot of memory and resources. So, Puppeteer headless browsers are a better choice here.</li></ol><h3>7 Best Practices Using Puppeteer Headless</h3><ol><li><strong>Manage Resource Usage</strong>: Since Puppeteer in headless mode runs without a graphical interface, it’s faster and uses fewer resources. However, it’s still essential to manage memory and CPU usage, especially when running multiple instances. Utilize Puppeteer’s built-in features like page pooling and efficient tab management to reduce resource consumption.</li><li><strong>Handle Timeouts and Retries</strong>: Web scraping or automated tasks may encounter network delays or timeouts. Setting proper timeout values and implementing retry logic ensures your scripts can handle intermittent failures without crashing.</li><li><strong>Wait for Elements Wisely</strong>: Always wait for the required elements to load before performing actions. Instead of using static delays (e.g., page.waitForTimeout), prefer waiting for specific events or elements (page.waitForSelector), which makes your automation more efficient and resilient to varying load times.</li><li><strong>Use Incognito Contexts for Isolation</strong>: To avoid data leakage and ensure each test or scrape runs in a clean environment, use incognito contexts (browser.createIncognitoBrowserContext). This prevents cached data, cookies, or local storage from affecting subsequent sessions.</li><li><strong>Leverage Headless Detection Bypassing</strong>: Many websites detect headless browsers and may block or serve limited content to these requests. Using techniques like modifying browser flags, overriding the user agent, and spoofing web features (e.g., navigator.webdriver removal) can help bypass headless detection.</li><li><strong>Monitor Performance and Logs</strong>: Use Puppeteer’s performance and console logging tools to debug and optimize scripts. Monitoring page performance metrics and handling browser logs can help diagnose bottlenecks and other issues.</li><li><strong>Optimize for Scalability</strong>: If you plan to run Puppeteer on a large scale, consider containerization with Docker, using load balancers, and running multiple browser instances in parallel. These steps help ensure scalability and reduce downtime in production environments.</li></ol><h3>The Bottom Lines</h3><p>Puppeteer headless browser makes everything easy. In this blog, we aim to share with you:</p><ul><li>the powerful functions</li><li>and efficient steps to use Puppeteer headless mode with Browserless</li></ul><p>The Browserless of Nstbrowser simplifies the configuration and operation of Puppeteer. Just like before, it’s time to reach out: <a href="https://www.nstbrowser.io/en/blog/tag/Browserless">how Browserless works</a> with Playwright and Puppeteer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2a3b2a499a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pyppeteer: How to Use Puppeteer in Python with Browserless?]]></title>
            <link>https://medium.com/@pumpkingee/pyppeteer-how-to-use-puppeteer-in-python-with-browserless-7b2386e2a582?source=rss-de43916695e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b2386e2a582</guid>
            <category><![CDATA[pyppeteer]]></category>
            <category><![CDATA[browserless]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Parker Montgomery]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 09:22:27 GMT</pubDate>
            <atom:updated>2024-10-09T09:22:27.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rvl0lhL2MQ7iwmBL" /></figure><h3>What Is Pyppeteer in Python?</h3><p>Pyppeteer is a Python port of the popular Node.js library Puppeteer, which is used to control headless Chrome or Chromium browsers programmatically.</p><p>Essentially, Pyppeteer allows Python developers to automate tasks within a web browser, such as scraping web pages, testing web applications, or interacting with websites as if a real user were doing so, but without a graphical interface.</p><h3>What is Browserless?</h3><p>Browserless is a cloud-based browser solution that allows for efficient browser automation, site scraping, and testing.</p><p>It makes use of Nstbrowser’s fingerprint library to enable random fingerprint switching, resulting in seamless data collecting and automation. Browserless’ robust cloud infrastructure makes it easier to manage automated activities by allowing access to several browser instances simultaneously.</p><blockquote><em>Do you have any wonderful ideas and doubts about web scraping and Browserless?<br>Let’s see what other developers are sharing on </em><a href="https://discord.com/invite/7Bgefnycx6"><strong><em>Discord</em></strong></a><em> and </em><a href="https://t.me/+GTaFK2QAz605Mzg1"><strong><em>Telegram</em></strong></a><em>!</em></blockquote><h3>What Can Pyppeteer Be used to Do?</h3><h3>Screenshot using Pyppeteer</h3><p>When using Browserless, you cannot see any screen, so when we need to know the specific screen of the browser in some links, it is recommended that you use the <strong>screenshot API</strong> to obtain the screenshot.</p><p>Executing the following script will generate a screenshot named <strong>youtube_screenshot.png</strong> in the current script path:</p><pre>import asyncio<br>from pyppeteer import connect<br><br>async def main():<br>    # Connect to the browser<br>    browser = await connect(browserWSEndpoint=browser_ws_endpoint)<br>    print(&quot;Connected!&quot;)<br>        <br>    # Create a new page<br>    page = await browser.newPage()<br>    <br>    # Visit youtube<br>    await page.goto(&quot;https://www.youtube.com/&quot;)<br>    # take a screenshot<br>    await page.screenshot({&quot;path&quot;: &quot;youtube_screenshot.png&quot;})<br>    await page.close()<br>    <br>asyncio.run(main())</pre><h3>Interact with dynamic pages</h3><p>On modern websites, JavaScript is relied upon to dynamically update content. For example, social media platforms often use infinite scrolling on their posts, and the loading of page data also requires waiting for the response of the backend, as well as a variety of form operations and various browser events.</p><p>Yes, Pyppeteer can also do the same: waiting for loading, clicking buttons, entering forms, and other browser operations.</p><h4>1. Waiting for the page to load</h4><p>The commonly used APIs for waiting for page loading are waitForSelector and waitFor.</p><ul><li>waitForSelector is mainly used to ensure that a certain element in the page is loaded normally</li><li>waitFor simply waits for a specified time.</li></ul><pre>import asyncio<br>from pyppeteer import connect<br><br>async def main():<br>    # Connect to the browser<br>    browser = await connect(browserWSEndpoint=browser_ws_endpoint)<br>    print(&quot;Connected!&quot;)<br><br>    # Visit nasa<br>    page = await browser.newPage()<br>    await page.goto(&quot;https://www.disney.com/&quot;)<br><br>    # Wait for news to load<br>    await page.waitForSelector(&#39;.content-body&#39;)<br>    # wait another 2 seconds<br>    await page.waitFor(2000)<br>    # take a screenshot<br>    await page.screenshot({&quot;path&quot;: &quot;disney.png&quot;})<br>    await page.close()<br>    <br>asyncio.run(main())</pre><h4>2. Scrolling the page</h4><p>On page.evaluate, you can set the position of the scroll bar by calling the window API, which is very convenient.</p><pre>import asyncio<br>from pyppeteer import connect<br><br>async def main():<br>    # Connect to the browser<br>    browser = await connect(browserWSEndpoint=browser_ws_endpoint)<br>    print(&quot;Connected!&quot;)<br><br>    # Visit HBO Max<br>    page = await browser.newPage()<br>    await page.goto(&#39;https://www.max.com/&#39;);<br><br>    # Scroll to the bottom<br>    await page.evaluate(&quot;window.scrollTo(0, document.documentElement.scrollHeight)&quot;);<br>    # take a screenshot<br>    await page.screenshot({&quot;path&quot;: &quot;HBOMax.png&quot;})<br>    await page.close()<br>    <br>asyncio.run(main())</pre><h4>3. Click the button</h4><p>In Python Pyppeteer, we can use page.click to click a button or hyperlink. Setting the input delay makes it more like a real user&#39;s operation.</p><p>The following is a simple example.</p><pre>import asyncio<br>from pyppeteer import connect<br><br>async def main():<br>    # Connect to the browser<br>    browser = await connect(browserWSEndpoint=browser_ws_endpoint)<br>    print(&quot;Connected!&quot;)<br><br>    page = await browser.newPage()<br>    await page.goto(&quot;https://example.com/&quot;)<br><br>    # click link<br>    await page.click(&quot;p &gt; a&quot;, {&quot;delay&quot;: 200})<br>    # take a screenshot<br>    await page.screenshot({&quot;path&quot;: &quot;example.png&quot;})<br>    await page.close()<br>    <br>asyncio.run(main())</pre><h4>4. Form input</h4><p>How to input data using Python Pyppeteer? Please use the page.type to enter content in the specified input box.</p><pre>import asyncio<br>from pyppeteer import connect<br><br>async def main():<br>    # Connect to the browser<br>    browser = await connect(browserWSEndpoint=browser_ws_endpoint)<br>    print(&quot;Connected!&quot;)<br><br>    # Create a new page<br>    page = await browser.newPage()<br>    # Visit chrome developer<br>    await page.goto(&quot;https://developer.chrome.com/&quot;)<br>    await page.setViewport({&quot;width&quot;: 1920, &quot;height&quot;: 1080})<br><br>    # Input content in the search box<br>    await page.type(&quot;.devsite-search-field&quot;, &quot;headless&quot;, {&quot;delay&quot;: 200})<br><br>    # take a screenshot<br>    await page.screenshot({&quot;path&quot;: &quot;developer.png&quot;})<br>    await page.close()<br>    <br>asyncio.run(main())</pre><h3>Login using Pyppeteer</h3><p>After the above examples, we can easily think of the interactions involved in login, such as the input type operation and the button click operation.</p><p>So, in the following example, let’s change the writing method. We will try to log in to the <a href="https://app.nstbrowser.io/">Nstbrowser Client</a>. After logging in, I will take a screenshot to verify whether it is successful.</p><pre>import asyncio<br>from pyppeteer import connect<br><br>async def main():<br>    # Connect to the browser<br>    browser = await connect(browserWSEndpoint=browser_ws_endpoint)<br>    print(&quot;Connected!&quot;)<br><br>    # Visit Nstbrowser Client<br>    page = await browser.newPage()<br>    await page.goto(&quot;https://app.nstbrowser.io/account/login&quot;)<br><br>    await page.waitForSelector(&quot;input&quot;)<br>    inputs = await page.querySelectorAll(&quot;input&quot;)<br>    # Enter your email address in the first input box<br>    await inputs[0].type(&quot;18552540330@163.com&quot;, delay=100)<br>    # Enter your password in the second input box<br>    await inputs[1].type(&quot;9KLYUWn3GmrzHPRGQl0EZ1QP3OWPFwcB&quot;, delay=100)<br>    <br>    buttons = await page.querySelectorAll(&quot;button&quot;)<br>    # Click the login button<br>    await buttons[1].click()<br><br>    # Waiting for login request response<br>    login_url = &quot;https://api.nstbrowser.io/api/v1/passport/login&quot;<br>    await page.waitForResponse(lambda res: res.url == login_url)<br>    await page.waitFor(2000)<br><br>    # take a screenshot<br>    await page.screenshot({&quot;fullPage&quot;: True, &quot;path&quot;: &quot;./nstbrowser.png&quot;})<br>    await page.close()<br><br>asyncio.run(main())</pre><ul><li>Running result:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*eX3-WSDjKbdt51dy.png" /></figure><p>We can see that our project has been redirected to the home page, which indicates that we have logged in to Nstbrowser successfully!</p><h3>How to Use Pyppeteer in Browserless?</h3><p>Could Pyppeteer work with Browserless?</p><p>Definitely, you can find the specific steps to integrate Pyppeteer into Browserless!</p><h3>Step1: Get the API KEY</h3><p>Before we start, we need to have a Browserless service. Using Browserless can solve complex web crawling and large-scale automation tasks, and it has now achieved fully managed cloud deployment.</p><p>Browserless adopts a browser-centric approach, provides powerful headless deployment capabilities, and provides higher performance and reliability. For more information about Browserless, you can <a href="https://apidocs.nstbrowser.io/doc-639323">click here</a> to learn more.</p><p>Get the API KEY and go to the Browserless menu page of the Nstbrowser client, or you can <a href="https://app.nstbrowser.io/app/browserless">click here</a> to access</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yderD1Qweod8uCQ8.png" /></figure><h3>Step2: Install Pyppeteer</h3><p>Pyppeteer is the Python version of Puppeteer, which provides similar functionality and allows developers to control headless browsers using Python scripts. It enables developers to automate interactions with web pages through Python code and is very commonly used in scenarios such as crawlers, testing, and data capture.</p><pre>pip install pyppeteer</pre><h3>Step3: Connect Pyppeteer to Browserless</h3><p>We need to prepare the following code. Just fill in your <strong>API key</strong> and <strong>proxy</strong> to connect to Browserless.</p><pre>from urllib.parse import urlencode<br>import json<br><br>token = &quot;your api key&quot; # &#39;required&#39;<br>config = {<br>    &quot;proxy&quot;: &quot;your proxy&quot;,  # required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080<br>    # &quot;platform&quot;: &quot;windows&quot;,  # support: windows, mac, linux<br>    # &quot;kernel&quot;: &#39;chromium&#39;, # only support: chromium<br>    # &quot;kernelMilestone&quot;: &#39;128&#39;, # support: 128<br>    # &quot;args&quot;: {<br>    #     &quot;--proxy-bypass-list&quot;: &quot;detect.nstbrowser.io&quot;<br>    # }, # browser args<br>    # &quot;fingerprint&quot;: {<br>    #     userAgent: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36&#39;, # userAgent supportted since v0.15.0<br>    # },<br>}<br>query = urlencode({&quot;token&quot;: token, &quot;config&quot;: json.dumps(config)})<br>browser_ws_endpoint = f&quot;ws://less.nstbrowser.io/connect?{query}&quot;token = &quot;your api key&quot; # &#39;required&#39;<br>config = {<br>    &quot;proxy&quot;: &quot;your proxy&quot;,  # required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080<br>    # &quot;platform&quot;: &quot;windows&quot;,  # support: windows, mac, linux<br>    # &quot;kernel&quot;: &#39;chromium&#39;, # only support: chromium<br>    # &quot;kernelMilestone&quot;: &#39;128&#39;, # support: 128<br>    # &quot;args&quot;: {<br>    #     &quot;--proxy-bypass-list&quot;: &quot;detect.nstbrowser.io&quot;<br>    # }, # browser args<br>    # &quot;fingerprint&quot;: {<br>    #     userAgent: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36&#39;, # userAgent supportted since v0.15.0<br>    # },<br>}<br>query = urlencode({&quot;token&quot;: token, &quot;config&quot;: json.dumps(config)})<br>browser_ws_endpoint = f&quot;ws://less.nstbrowser.io/connect?{query}&quot;</pre><p>Connected and let’s start scraping!</p><pre>import asyncio<br>from pyppeteer import connect<br><br>async def main():<br>    # Connect to the browser<br>    browser = await connect(browserWSEndpoint=browser_ws_endpoint)<br>    print(&quot;Connected!&quot;)<br>    <br>asyncio.run(main())async def main():<br>    # Connect to the browser<br>    browser = await connect(browserWSEndpoint=browser_ws_endpoint)<br>    print(&quot;Connected!&quot;)<br>    <br>asyncio.run(main())</pre><h3>Step4: Using Pyppeteer in the Browserless</h3><p>In this blog, we will go into a simple case to help you quickly get started with Browserless — crawling Books to Scrape.</p><p>In the following example, we try to crawl all the book titles on the current page:</p><ul><li>Open the page</li><li>Wait for the page to load normally</li><li>Open the debug console</li><li>Determine the HTML element corresponding to the book title at any location:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*35qqCEkZshG_b7tL.png" /></figure><ul><li><strong>Scripts:</strong></li></ul><pre>import asyncio<br>from pyppeteer import connect<br><br>async def main():<br>    # Connect to the browser<br>    browser = await connect(browserWSEndpoint=browser_ws_endpoint)<br>    print(&quot;Connected!&quot;)<br><br>    # Create a new page<br>    page = await browser.newPage()<br><br>    # Visit Books to Scrape<br>    await page.goto(&quot;http://books.toscrape.com/&quot;)<br><br>    # Wait for book list to load<br>    await page.waitForSelector(&quot;section&quot;)<br><br>    # Select all book title elements<br>    books = await page.querySelectorAll(&quot;article.product_pod &gt; h3 &gt; a&quot;)<br><br>    # loop through all elements to extract titles<br>    for book in books:<br>        title_element = await book.getProperty(&quot;textContent&quot;)<br>        title = await title_element.jsonValue()<br>        print(f&quot;[{title}]&quot;)<br>    <br>    await page.close()<br><br># Run the script<br>asyncio.run(main())</pre><ul><li><strong>Results:</strong></li></ul><p>Running the above script will output all captured data in the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*YKUR59m-PC0NSn3O.png" /></figure><h3>Step5: Check the data in the Browserless Dashboard</h3><p>You can view statistics for recent requests and remaining session time in the Browserless menu of the Nstbrowser client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kKfyh80U6vnrHaPb.png" /></figure><h3>Common Errors When Using Pyppeteer</h3><p>Most developers may encounter some errors while setting up and using Pyppeteer. Don’t worry! You can find out how to fix them here.</p><h3>Error 1: Pyppeteer cannot be installed</h3><p>While installing Pyppeteer, you may encounter the error “Unable to install Pyppeteer”.</p><p>Please check the Python version on your system. Pyppeteer only supports Python 3.6+. Therefore, please try to <strong>upgrade Python and reinstall Pyppeteer</strong>.</p><h3>Error 2: Pyppeteer browser closed unexpectedly</h3><p>You may encounter this error: pyppeteer.errors.BrowserError: Browser closed unexpectedly when you execute a Pyppeteer Python script for the first time after installation.</p><p>This means that all Chromium dependencies are not fully installed. Please install the Chrome driver manually using the following command:</p><pre>pyppeteer-install</pre><h3>Take Away Notes</h3><p>Pyppeteer is an unofficial Python port of the classic Node.js Puppeteer library. It is an easy-to-install, lightweight, and fast package for web automation and dynamic website scraping.</p><p>In this blog, you have learned:</p><ul><li>What is Pyppeteer?</li><li>Specific steps to integrate Pyppeteer with Browserless.</li><li>Other use cases of Pyppeteer.</li></ul><p>If you want to know more about the features of Browserless, please check out the <a href="https://apidocs.nstbrowser.io/doc-639323?nav=1">official manual</a>. Nstbrowser provides you with the best cloud browser to solve the local limitations of automation work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b2386e2a582" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Run Automated Tests with Puppeteer and Browserless?]]></title>
            <link>https://medium.com/@pumpkingee/how-to-run-automated-tests-with-puppeteer-and-browserless-7f36614331fe?source=rss-de43916695e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f36614331fe</guid>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[browserless]]></category>
            <dc:creator><![CDATA[Parker Montgomery]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 03:59:18 GMT</pubDate>
            <atom:updated>2024-10-08T03:59:18.461Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YEcI0hugyt5F1O7Q" /></figure><h3>Puppeteer: What Is It &amp; Features</h3><p>Puppeteer is a Node.js library. With Puppeteer, you can test your websites on all Chromium-based browsers, including Chrome, Microsoft Edge Chrome, and Chromium. In addition, Puppeteer can be used for web scraping, automation, and testing purposes.</p><p>Since Puppeteer communicates only over the DevTools protocol, only browsers that implement this protocol are supported. Therefore, Safari (WebKit), Firefox, and IE are not supported yet.</p><h3>What Is Headless Browser Testing?</h3><p>Headless browser testing allows web pages to be controlled automatically without the use of a graphical user interface (GUI).</p><p>This enables testers, users, QA teams, or developers to conduct automated testing on web applications without manually interacting with the browser seen on a display.</p><p>Essentially, headless browser testing works like that, though it’s usually done through a simple script. It accelerates the testing process and delivers fast feedback during development.</p><h3>What Is Browserless?</h3><p>Browserless is a powerful cloud-based solution for seamless browser automation, web scraping, and testing. It leverages Nstbrowser’s advanced fingerprint library for random fingerprint switching, ensuring uninterrupted data collection and automation.</p><p>With its strong cloud infrastructure, Browserless allows easy access to multiple browser instances, simplifying the management of automation tasks.</p><blockquote><em>Do you have any wonderful ideas and doubts about web scraping and Browserless?<br>Let’s see what other developers are sharing on </em><a href="https://discord.com/invite/7Bgefnycx6"><strong><em>Discord</em></strong></a><em> and </em><a href="https://t.me/+GTaFK2QAz605Mzg1"><strong><em>Telegram</em></strong></a><em>!</em></blockquote><h3>Why Is Puppeteer Better than Similar Testing Platforms?</h3><ul><li><strong>Powerful feature set</strong>: Puppeteer provides full control over Chrome and Chromium browsers, supporting automated tasks such as page navigation, form filling, screenshots, PDF generation, etc. It can simulate user operations in the browser for highly complex testing.</li><li><strong>Headless mode</strong>: Puppeteer supports headless browser mode, which makes it more efficient and lightweight when performing automated tasks in the background, without loading a graphical interface, improving speed and resource utilization.</li><li><strong>Cross-browser support</strong>: In addition to Chromium, Puppeteer also supports cross-browser testing through the WebDriver protocol, with strong compatibility and adaptability to multiple browser environments.</li><li><strong>Community support and complete documentation</strong>: Puppeteer has an active developer community and detailed documentation, allowing developers to get started quickly and get support from the community.</li><li><strong>Tight integration with Chrome</strong>: Puppeteer’s deep integration with Chrome/Chromium makes it excel in browser automation tasks, especially in page performance monitoring and crawling accuracy.</li></ul><h3>Puppeteer Automated Tests with Browserless</h3><p>Let’s test the login function of Nstbrowser’s dashboard. We need to</p><ul><li>visit the <a href="https://app.nstbrowser.io/login"><strong>Nstbrowser Client</strong></a></li><li>then fill in the account and password through the puppeteer’s automation program</li><li>and finally, click the login button to log in</li></ul><h3>Step 1: Install Puppeteer.</h3><p>Here we choose the more lightweight puppeteer-core:</p><pre>pnpm install puppeteer-core</pre><h3>Step 2: Get your API Key.</h3><p>We can find your API Key in the Browserless panel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cu9fBYFkK45E0Q13.png" /></figure><h3>Step 3: Connect to Browserless</h3><pre>import puppeteer from &quot;puppeteer-core&quot;;<br><br>const token = &quot;your api key&quot;;<br><br>const config = {<br>    proxy: &#39;your proxy&#39;, // required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080<br>    // platform: &#39;windows&#39;, // support: windows, mac, linux<br>    // kernel: &#39;chromium&#39;, // only support: chromium<br>    // kernelMilestone: &#39;128&#39;, // support: 128<br>    // args: {<br>    //     &quot;--proxy-bypass-list&quot;: &quot;detect.nstbrowser.io&quot;<br>    // }, // browser args<br>    // fingerprint: {<br>    //     userAgent: &#39;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36&#39;, // userAgent supportted since v0.15.0<br>    // },<br>};<br><br>const query = new URLSearchParams({<br>  token: token, // required<br>  config: JSON.stringify(config),<br>});<br><br>const browserWSEndpoint = `https://less.nstbrowser.io/connect?${query.toString()}`;<br><br>const getBrowser = async () =&gt;<br>  puppeteer.connect({<br>    browserWSEndpoint,<br>    defaultViewport: null,<br>  });<br><br>const main = async (req, res) =&gt; {<br>  try {<br>    const browser = await getBrowser();<br>    const page = await browser.newPage();<br>    await page.goto(&quot;https://app.nstbrowser.io/login&quot;);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>};<br><br>main();</pre><p>Now that, we have successfully connected Browserless and accessed our target website, let’s complete the test flow and verify the results by taking screenshots.</p><pre>await page.waitForSelector(&#39;input&#39;);<br><br>const inputs = await page.$$(&#39;input&#39;);<br><br>await inputs[0].type(&#39;18552540330@163.com&#39;, { delay: 100 });<br>await inputs[1].type(&#39;9KLYUWn3GmrzHPRGQl0EZ1QP3OWPFwcB&#39;, { delay: 100 });<br><br>const buttons = await page.$$(&#39;button&#39;);<br>await buttons[1].click();<br><br>await page.waitForResponse((req) =&gt; {<br>  const url = &quot;https://api.nstbrowser.io/api/v1/passport/login&quot;;<br>  if (req.url() === url) {<br>    return true;<br>  }<br>});<br><br>await page.screenshot({ fullPage: true, path: &quot;./nstbrowser.png&quot; });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*tAw-IF0jzowEHwnn.png" /></figure><p>We can see that we have successfully logged into Nstbrowser and are being redirected to the dashboard, indicating that our test has passed.</p><h3>Difference Between Puppeteer and Other Platforms</h3><p>Here is a detailed comparison between Puppeteer and various other testing platforms:</p><ol><li><strong>Puppeteer vs. WebKit/Blink:</strong></li></ol><ul><li>Puppeteer is a Node.js library providing a high-level API to control headless Chrome or Chromium browsers.</li><li>WebKit and Blink are layout engines used by Safari and Chromium browsers, respectively. They are responsible for rendering web pages, while Puppeteer controls the browser for automation tasks.</li></ul><p><strong>2. Puppeteer vs. Selenium:</strong></p><ul><li>Puppeteer directly communicates with Chrome/Chromium via the debugging protocol, making it tightly integrated with these browsers.</li><li>Selenium uses Chromedriver to manage and control browsers, which allows it to support multiple browsers (e.g., Firefox, Safari, Edge). Puppeteer, on the other hand, is Chrome/Chromium-focused.</li></ul><p><strong>3. Puppeteer vs. PhantomJS:</strong></p><ul><li>Puppeteer is a modern Node.js-based library that controls headless Chrome/Chromium.</li><li>PhantomJS is a headless browser based on WebKit/Blink. However, PhantomJS is outdated and no longer actively maintained, which makes Puppeteer a more reliable and efficient choice for most automation tasks.</li></ul><p><strong>4. Puppeteer vs. Nightmare.js:</strong></p><ul><li>Puppeteer uses the Chrome DevTools Protocol to control Chrome/Chromium, giving it deep access to the browser’s functionality.</li><li>Nightmare.js is a JavaScript library that uses Electron to render web pages. It was built for ease of use but lacks the performance and modern browser support that Puppeteer offers.</li></ul><p><strong>5. Puppeteer vs. Cypress:</strong></p><ul><li>Puppeteer is a Node.js library that automates browser tasks like web scraping, PDF generation, and screenshot capturing.</li><li>Cypress is a JavaScript-based end-to-end testing framework designed for testing web applications. It provides a user-friendly interface for writing tests and handles asynchronous operations automatically, making it ideal for frontend testing.</li></ul><h3>Ending Thoughts</h3><p>Puppeteer is a powerful and wonderful tool for finishing web testing. With Browserless, you can conduct Puppeteer to do any automation tasks.</p><p>I hope this article opens up a whole new world of website test automation for you. As always, be sure to check out the <a href="https://www.nstbrowser.io/en/blog/tag/All"><strong>Nstbrowser blog</strong></a> and <a href="https://docs.nstbrowser.io/"><strong>documentation tutorials</strong></a> for more exciting web browser automation content! Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f36614331fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Do Web Scraping in Golang Using Colly?]]></title>
            <link>https://medium.com/@pumpkingee/how-to-do-web-scraping-in-golang-using-colly-d4bc01a3a0d3?source=rss-de43916695e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4bc01a3a0d3</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Parker Montgomery]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 09:22:21 GMT</pubDate>
            <atom:updated>2024-09-30T09:22:21.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wA56qak4ntsgSiij" /></figure><h3>What Is Colly?</h3><p>Go is a versatile language with packages and frameworks that can do almost everything.</p><p>Today, we will use a framework called Colly, which is an efficient and powerful web scraping framework written in Go for scraping data on the web. It provides a simple and easy-to-use API that allows developers to quickly build crawlers to visit web pages and extract the required information.</p><p>What is Colly?</p><p>Colly provides a set of convenient and powerful tools for extracting data from websites, automating network interactions, and building web scraping tools.</p><p>In this article, you will get some practical experience using Colly and learn how to scrap data from the web with Golang: Colly.</p><h3>How Does Colly Work?</h3><p>The core part of Colly is Collector. It is responsible for executing HTTP requests and allows you to define how to handle requests and responses. By calling c := colly.NewCollector(), you can create a new Collector instance, which can then be used to initiate network requests and process data.</p><h3>Core functions:</h3><p><strong>1.</strong> <strong>Visit</strong> and <strong>Request</strong> methods:</p><ul><li>Visit: This is the most commonly used request method, which directly accesses the target web page.</li><li>Request: Allows you to attach some additional information (such as custom headers or parameters) when sending a request, which is used for more complex request scenarios.</li></ul><p><strong>2. Callback mechanism</strong>: Colly relies on callback functions to execute at different stages of the request life cycle. Collector provides a variety of callback registration methods, mainly including the following six:</p><ul><li>OnRequest: Triggered before sending an HTTP request, you can add custom headers, print request information, etc.</li><li>OnError: Triggered when an error occurs during the request process, used to capture and handle request failures.</li><li>OnResponse: Triggered after receiving the server&#39;s response, which can be used to process response data.</li><li>OnHTML: Triggered when HTML content is received and matches the specified CSS selector, used to extract data from HTML pages.</li><li>OnXML: Triggered when the response content is XML or HTML and can be used to process XML-formatted content.</li><li>OnScraped: Triggered after all requested data is processed, and is the callback at the end of the crawling task.</li></ul><p><strong>3. OnHTML callback:</strong></p><ul><li>The most commonly used callback function, registered using CSS Selector, when Colly finds a matching element in the HTML DOM, the registered callback function is called.</li><li>Colly uses the goquery library to parse HTML and match CSS selectors, and the goquery API is similar to jQuery, so jQuery-style selectors can be used to extract data from the page.</li></ul><blockquote><em>Do you have any wonderful ideas and doubts about web scraping and Browserless?<br>Let’s see what other developers are sharing on </em><a href="https://discord.com/invite/7Bgefnycx6"><strong><em>Discord</em></strong></a><em> and </em><a href="https://t.me/+GTaFK2QAz605Mzg1"><strong><em>Telegram</em></strong></a><em>!</em></blockquote><h3>How to Scrap Data from Web with Golang?</h3><h3>Step 1. Environment preparation</h3><h4>Golang installation</h4><p>Go to the Golang official website, and select the appropriate version to download and install. We recommend go1.20+. This tutorial uses go1.23.1.</p><p>After the installation is complete, you can verify whether the installation is successful by using the terminal:</p><pre>go version</pre><p>The successful output of the go version information indicates that the installation is successful.</p><h4>Choose a suitable IDE</h4><p>Choose a suitable IDE according to your preference. Visual Studio is recommended.</p><h3>Step 2. Project construction</h3><p>Next, start creating a project.</p><ul><li>Create a project directory:</li></ul><pre>mkdir gocolly-browserless &amp;&amp; cd gocolly-browserless</pre><ul><li>Initialize the Go project:</li></ul><pre>go mod init colly-scraper</pre><p>The above command executes go mod init to initialize a go project named colly-scraper, and generates a go.mod file in the project directory with the following content:</p><pre>module colly-scraper<br><br>go 1.23.1</pre><ul><li>Then create main.go and create the main method:</li></ul><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>    fmt.Println(&quot;Hello Nstbrowser!&quot;)<br>}</pre><ul><li>Run the main method:</li></ul><pre>go run main.go</pre><p>If you see the printed information successfully, it means the operation is successful. The project has been successfully built.</p><h3>Step 3. Use Colly</h3><p>Well done! All the preparations have been completed. Next, we will officially start using Colly to complete some simple data crawling.</p><h4>Install Colly</h4><p>Enter the following command under the project root path to complete the Colly installation:</p><pre>go get github.com/gocolly/colly</pre><p>If the installation process reports an error that the current go version is not supported, you can choose to install a lower version of Colly or upgrade Golang to the corresponding version. After installing Colly, the go.mod is as follows:</p><pre>module colly-scraper<br><br>go 1.23.1<br><br>require (<br>    github.com/gocolly/colly v1.2.0 // indirect<br>    ...<br>)</pre><h4>Core Principle</h4><p>The core working principle of Colly is to obtain web page content through HTTP requests, and then parse the DOM structure in the web page to extract the specific data we need. Its workflow can be divided into the following steps:</p><ol><li><strong>Create Collector</strong>: This is the core object used by Colly to initiate HTTP requests and process responses.</li><li><strong>Define callback functions</strong>: Colly processes specific elements or events (such as clicking links, parsing forms, etc.) when parsing HTML by registering callback functions.</li><li><strong>Visit the target website</strong>: By calling the Visit() method, the Collector will initiate a request to the specified URL.</li><li><strong>Process the response data</strong>: Process the HTML data in the callback function to extract the required information.</li></ol><p><strong>Getting Started Example</strong></p><p>The following is a simple example of visiting the <a href="https://nstbrowser.io/">Nstbrowser official website</a></p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br><br>    &quot;github.com/gocolly/colly&quot;<br>)<br><br>func main() {<br>    // Create a new collector<br>    c := colly.NewCollector()<br><br>    // Callback function, invoked when the crawler finds a &lt;title&gt; element<br>    c.OnHTML(&quot;title&quot;, func(e *colly.HTMLElement) {<br>        fmt.Println(&quot;Page Title:&quot;, e.Text)<br>    })<br><br>    // Handle errors<br>    c.OnError(func(_ *colly.Response, err error) {<br>        fmt.Println(&quot;Error:&quot;, err)<br>    })<br><br>    // Visit the target page<br>    c.Visit(&quot;https://nstbrowser.io&quot;)<br>}</pre><p>After executing the above code, the crawler will output the content of the title element of the page. This is Colly&#39;s basic workflow, which allows it to easily parse HTML and extract the information you need. Running go run main.go will print information similar to the following:</p><pre>Page Title: Nstbrowser - Advanced Anti-Detect Browser for Web Scraping and Multiple Accounts Managing</pre><h4>Common settings</h4><p>Colly is a powerful and flexible Golang crawler framework that can control the behavior of the crawler through configuration. The following will introduce the commonly used configuration options in Colly in detail, and explain its usage scenarios and implementation methods.</p><ol><li>Collector configuration</li></ol><p>The colly.NewCollector is used to create a new Collector instance, which is the core part of the crawler. By passing different configuration options, you can customize the behavior of the crawler, such as limiting the crawled domain names, the maximum crawling depth, asynchronous crawling, etc.</p><blockquote><strong><em>Example</em></strong></blockquote><pre>c := colly.NewCollector(<br>    colly.AllowedDomains(&quot;example.com&quot;),   // Restrict to certain domains<br>    colly.MaxDepth(3),                     // Limit the depth of the crawl<br>    colly.Async(true),                     // Enable asynchronous scraping<br>    colly.IgnoreRobotsTxt(),               // Ignore robots.txt rules<br>    colly.DisallowedURLFilters(regexp.MustCompile(&quot;.*.jpg&quot;)), // Skip certain URLs<br>    ...<br>)</pre><p>2. Request Configuration</p><p>Colly provides multiple methods to configure HTTP request behavior, such as setting custom request headers, proxies, cookies, etc. Through these settings, the crawler can simulate the behavior of real users and bypass some anti-crawler mechanisms.</p><blockquote><strong><em>Custom UA header</em></strong></blockquote><p>You can set custom HTTP header information for each request through the Headers.Set method. For example, set User-Agent to simulate the browser’s access behavior to avoid being intercepted by anti-crawler mechanisms.</p><pre>c.OnRequest(func(r *colly.Request) {<br>    r.Headers.Set(&quot;User-Agent&quot;, &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36&quot;)<br>    ...<br>})</pre><blockquote><strong><em>Cookie Management</em></strong></blockquote><p>Colly automatically handles cookies by default, but you can also manually set specific cookies. For example, when crawling certain pages that require a login, you can pre-set cookies after login.</p><pre>c.SetCookies(&quot;http://example.com&quot;, []*http.Cookie{<br>    &amp;http.Cookie{<br>        Name:   &quot;session_id&quot;,<br>        Value:  &quot;1234567890&quot;,<br>        Domain: &quot;example.com&quot;,<br>    },<br>})</pre><blockquote><strong><em>Set up a proxy</em></strong></blockquote><p>Using a proxy server can hide your real IP address and bypass the IP-blocking policies of some websites. Colly supports single proxy and dynamic proxy switching.</p><pre>c.SetProxy(&quot;your proxy url&quot;)</pre><blockquote><strong><em>Set request timeout</em></strong></blockquote><p>When the website responds slowly, setting a request timeout can prevent the program from hanging for a long time. By default, Colly’s timeout is 10 seconds, and you can adjust the timeout as needed.</p><pre>c.SetRequestTimeout(30 * time.Second)</pre><blockquote><em>Callbacks</em></blockquote><p>Colly supports callback processing for various events, such as page loading success, element found, request error, etc. Through these callbacks, you can flexibly handle the crawled content or deal with errors in the crawling process.<br>Common callback examples:</p><ul><li>OnRequest</li></ul><p>This callback will be called before each request is sent. You can dynamically set the request header or other parameters here.</p><pre>c.OnRequest(func(r *colly.Request) {<br>    fmt.Println(&quot;Visiting:&quot;, r.URL.String())<br>})</pre><ul><li>OnResponse</li></ul><p>This callback is called when a response is received to process the original HTTP response data.</p><pre>c.OnResponse(func(r *colly.Response) {<br>    fmt.Println(&quot;Received:&quot;, string(r.Body))<br>})</pre><ul><li>OnHTML</li></ul><p>Used to process specific elements in HTML pages. When a matching HTML element appears on the page, this callback will be called to extract the required information.</p><pre>c.OnHTML(&quot;title&quot;, func(e *colly.HTMLElement) {<br>    fmt.Println(&quot;Page Title:&quot;, e.Text)<br>})</pre><ul><li>OnError</li></ul><p>This callback is called when an error occurs in the request. You can handle the exception here.</p><pre>c.OnError(func(_ *colly.Response, err error) {<br>    fmt.Println(&quot;Error:&quot;, err)<br>})</pre><p>3. Request Limitation</p><p>Colly also provides some options to optimize the performance of the crawler, such as limiting the number of concurrent requests, increasing the crawling speed, and setting a delay between requests.</p><pre>c.Limit(&amp;colly.LimitRule{<br>    DomainGlob:  &quot;*&quot;,             // DomainRegexp is a glob pattern to match against domains<br>    Delay:       3 * time.Second, // Delay is the duration to wait before creating a new request to the matching domains<br>    Parallelism: 2,               // Parallelism is the number of the maximum allowed concurrent requests of the matching domains<br>})</pre><p>For more settings, please refer to the official documentation of Colly.</p><h4>Advanced Example</h4><p>Combining the knowledge we have learned before, let’s crawl the classified information data on the homepage of Wikipedia and print the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cE-nJ9JjUgXf6wHv.png" /></figure><ol><li>Page element analysis</li></ol><p>After entering the homepage, we right click -&gt; inspect or press the F12 shortcut key to enter the page element analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*atLAZE31UxBkavJh.png" /></figure><p>We can find:</p><ul><li>The category information I need is the div element with the class name other-project, where the category link is the href attribute value in the a tag. Its class name is other-project-link.</li><li>Continue to follow up on this element and it shows that the two span class names (other-project-title and other-project-tagline) under the class element .other-project-text are its category name and introduction.</li></ul><p>Next, start coding to get the data we want.</p><p>2. Coding</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br><br>    &quot;github.com/gocolly/colly&quot;<br>)<br><br>func main() {<br>    // Create a new collector<br>    c := colly.NewCollector()<br><br>    // Handle errors<br>    c.OnError(func(_ *colly.Response, err error) {<br>        fmt.Println(&quot;Error:&quot;, err)<br>    })<br><br>    // Custom request header: User-Agent<br>    c.OnRequest(func(r *colly.Request) {<br>        r.Headers.Set(&quot;User-Agent&quot;, &quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36&quot;)<br>    })<br><br>    // Set proxy<br>    c.SetProxy(&quot;your proxy&quot;)<br><br>    // Set request timeout<br>    c.SetRequestTimeout(30 * time.Second)<br><br>    c.Limit(&amp;colly.LimitRule{<br>        DomainGlob:  &quot;*&quot;,             // DomainRegexp is a glob pattern to match against domains<br>        Delay:       1 * time.Second, // Delay is the duration to wait before creating a new request to the matching domains<br>        Parallelism: 2,               // Parallelism is the number of the maximum allowed concurrent requests of the matching domains<br>    })<br><br>    // Wait for elements with the class &quot;other-project-text&quot; to appear<br>    c.OnHTML(&quot;div.other-project&quot;, func(e *colly.HTMLElement) {<br>        link := e.ChildAttrs(&quot;.other-project-link&quot;, &quot;href&quot;)<br>        title := e.ChildText(&quot;.other-project-link .other-project-text .other-project-title&quot;)<br>        tagline := e.ChildText(&quot;.other-project-link .other-project-text .other-project-tagline&quot;) // project tagline<br>        fmt.Println(fmt.Sprintf(&quot;%s =&gt; %s(%s)&quot;, title, tagline, link))<br>    })<br><br>    // Visit the target page<br>    c.Visit(&quot;https://wikipedia.org&quot;)<br>}</pre><ul><li>Running project</li></ul><pre>go run main.go</pre><ul><li>Result</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/0*yNDcgWCmqB1Fuw6g.png" /></figure><h3>The Bottom Lines</h3><p>Stop here dears! Nstbrowser always helps you simplify every difficult step of web scraping and automation tasks. In this wonderful blog, we have learned that:</p><ul><li>How to build the basic environment of Colly.</li><li>Common Colly configuration and usage methods.</li><li>Use Colly to complete the visit to the <a href="https://nstbrowser.io/">Nstbrowser official website</a> and crawl the Wikipedia homepage Wiki classification data.</li></ul><p>Through simple examples, we have experienced the simplicity and powerful data crawling capabilities of Colly. For more advanced usage, please refer to the official Colly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4bc01a3a0d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Browserless with Ubuntu 22.04?]]></title>
            <link>https://medium.com/@pumpkingee/how-to-use-browserless-with-ubuntu-22-04-ad82e363b5a9?source=rss-de43916695e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad82e363b5a9</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[browserless]]></category>
            <dc:creator><![CDATA[Parker Montgomery]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 10:48:30 GMT</pubDate>
            <atom:updated>2024-09-26T10:48:30.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EEkd-cJy8gxUepHy" /></figure><p>Ubuntu 22.04 is a Debian-based Linux operating system that is a long-term support version (LTS), providing five years of official support and security updates.</p><p>It uses a modern GNOME desktop environment, optimizes performance and stability, and contains the latest packages and tools to support new hardware. In addition, Ubuntu 22.04 enhances security and provides stricter default security settings and privacy protection.</p><h3>Is Ubuntu 22.04 still supported?</h3><p>Yes!</p><p>Ubuntu 22.04 is codenamed Jammy Jellyfish. It was released on 21 April 2022 and is a long-term support release, supported for five years, until April 2027.</p><h3>What is Browserless?</h3><p>Browserless is a powerful browser solution. Based on cloud clusters, Browserless is designed to facilitate complex browser automation tasks, web crawling, and testing in a scalable and efficient manner. It is built on Nstbrowser’s comprehensive fingerprint library and provides random fingerprint switching to meet user needs for data collection and automation tasks.</p><h3>How to Use Browserless on Ubuntu 22.04?</h3><h3>Prerequisites</h3><p>Before using Browserless, you need to configure NodeJS in advance.</p><p>Ubuntu 22.04 comes with a Node.js package. Although the default version may not be the latest, it is sufficient to meet basic development needs. We use apt to install it, which is a simple way.</p><p><strong>Step 1.</strong> <strong>Update the local package index</strong></p><p>Before installing Node.js, update the local package index:</p><pre>sudo apt update</pre><p><strong>Step 2. Install Node.js</strong></p><p>Install Node.js using the apt package manager:</p><pre>sudo apt install nodejs -y</pre><p><strong>Step 3. Install the node package manager</strong></p><p>npm is used to manage Node.js modules and packages</p><pre>sudo apt install npm -y</pre><p><strong>Step 4. Verify that </strong><strong>Node.js and </strong><strong>npm are installed successfully</strong></p><p>After the installation is complete, you can check the installed Node.js version with the following command:</p><pre>node -v<br>npm -v</pre><p>If the output <strong>shows version information</strong>, it means the installation is successful.</p><h3>Using Browserless</h3><h4>Step 1. Project Construction</h4><ul><li>According to the <a href="https://apidocs.nstbrowser.io/folder-1444256">Nstbrowser browserless API documentation</a>, first, we need to obtain the <a href="https://app.nstbrowser.io/app/api">API Key</a>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a5rK4scz3xKsnVFX" /></figure><ul><li>Next, please create a node project</li></ul><pre>mkdir nst-browserless &amp;&amp; cd nst-browserless<br>npm init -y</pre><ul><li>Then, just choose the IDE whatever you like. We use <a href="https://code.visualstudio.com/">VisualStudio</a> here:</li></ul><pre>code .</pre><p>Currently, Browserless only supports <a href="https://apidocs.nstbrowser.io/doc-639326">Puppeteer</a> and <a href="https://apidocs.nstbrowser.io/doc-639336">Playwright</a>. In this tutorial, we choose to use a puppeteer. Next, it’s time to install the dependencies:</p><pre>npm i --save puppeteer-core</pre><p>So far, we have completed the project construction.</p><h4>Step 2. Coding</h4><blockquote><strong><em>Access Browserless</em></strong></blockquote><p>First, write a simple process to verify whether Browserless can be accessed normally:</p><pre>import puppeteer from &quot;puppeteer-core&quot;;<br><br>const token = &quot;your token&quot;; // required<br>const config = {<br>    proxy: &#39;your proxy&#39;, // required<br>};<br>const query = new URLSearchParams({<br>    token: token, // required<br>    config: JSON.stringify(config),<br>});<br>const browserWSEndpoint = `https://less.nstbrowser.io/connect?${query.toString()}`;<br><br>const getBrowser = async () =&gt; puppeteer.connect({<br>    browserWSEndpoint,<br>    defaultViewport: null,<br>});<br><br>(async () =&gt; {<br>    let browser = null;<br>    await getBrowser()<br>        .then(async (browser) =&gt; {<br>            const page = await browser.newPage();<br>            await page.goto(&quot;https://nstbrowser.io&quot;);<br>            await page.screenshot({ path: &quot;screenshot.png&quot;, fullPage: true });<br>            await page.close();<br>            await browser.close();<br>        })<br>        .catch((error) =&gt; {<br>            console.log(error);<br>        })<br>        .finally(() =&gt; browser?.close());<br>})()</pre><p>Being able to generate a screenshot shows that we can use Browserless normally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1CQsfjQCIrTBJvd0" /></figure><blockquote><strong><em>Scraping images</em></strong></blockquote><p>Next, we go to the Pixels site to crawl some images:</p><ul><li>enter the subpage from the Wall Art category navigation at the top of the homepage</li><li>get the first six image addresses and print the results.</li></ul><ol><li><strong>Site analysis</strong></li></ol><p>Find the navigation menu link:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e6Gnohov6ghSamT2" /></figure><p>After analysis, we can see that the link we need to click is an a tag under the li element with the id menuTopArt. Next, let&#39;s further analyze the element to be crawled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KJR0nsBWvZTbzwmm" /></figure><p>It shows that the element where the image we want is located in the src value of an img element with the class name of searchEngineFeaturedProductImage lazyloaded.</p><p><strong>2. Crawling images</strong></p><p>Modify the code we wrote earlier to complete the crawling work:</p><pre>import puppeteer from &quot;puppeteer-core&quot;;<br><br>const token = &quot;your api token&quot;;<br>const config = {<br>    proxy: &#39;your proxy&#39;, // required<br>};<br>const query = new URLSearchParams({<br>    token: token, // required<br>    config: JSON.stringify(config),<br>});<br>const browserWSEndpoint = `https://less.nstbrowser.io/connect?${query.toString()}`;<br><br>const getBrowser = async () =&gt; puppeteer.connect({<br>    browserWSEndpoint,<br>    defaultViewport: null,<br>});<br><br>(async () =&gt; {<br>    let browser = null;<br>    const pixelsWebsite = &quot;https://pixels.com&quot;;<br>    await getBrowser()<br>        .then(async (browser) =&gt; {<br>            const page = await browser.newPage();<br>            await page.goto(pixelsWebsite);<br>            await page.waitForSelector(&quot;#menuTopArt&quot;, { timeout: 30000 });<br>            await page.click(&quot;#menuTopArt a&quot;); // click &#39;Wall Art&#39; menu<br>            await page.waitForSelector(&quot;.searchEngineFeaturedProductImage&quot;, { timeout: 30000 });<br>            const imageElements = await page.$$(&#39;.searchEngineFeaturedProductImage&#39;);<br>            for (const imageElement of imageElements) {<br>                const src = await page.evaluate(el =&gt; el.src, imageElement);<br>                if (src.includes(&quot;Blank.jpg&quot;)) { // break if Blank.jgp comes<br>                    break<br>                }<br>                console.log(src);<br>                // TODO: Add further processing for the image if needed<br>            }<br>            await page.close();<br>            await browser.close();<br>        })<br>        .catch((error) =&gt; {<br>            console.log(error);<br>        })<br>        .finally(() =&gt; browser?.close());<br>})()</pre><p>Bravo! Here you can find the scraping result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ovHcofQwHsYaBOyO" /></figure><h3>Take Away Notes</h3><p>How wonderful Ubuntu is! In this blog, we learned that:</p><ul><li>The steps to install NodeJS on Ubuntu 22.04</li><li>Use <a href="https://apidocs.nstbrowser.io/folder-1444256"><strong>Browserless</strong></a> through Puppeteer to crawl the image address link data on the Pixels site</li></ul><p>You can see that the whole process is very light and fast, and the process is also very simple.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad82e363b5a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>