Ratkaistu: kuinka kaapata useita sivuja seleenillä Pythonissa

Viimeisin päivitys: 09/11/2023

Suurin ongelma useiden sivujen kaapimisessa Seleniumia käyttämällä Pythonissa on, että se voi olla aikaa vievää ja vaikeaa saada haluamasi tulokset.

Yritän kaapia useita sivuja seleenillä pythonissa. Olen kokeillut seuraavaa koodia, mutta se kaapii vain ensimmäisen sivun. Miten saan sen kaapimaan kaikki sivut?

from selenium import webdriver
from bs4 import BeautifulSoup as soup
import pandas as pd

my_url = 'https://www.flipkart.com/search?q=iphone&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off'

#Opening up connection and grabbing the page
uClient = uReq(my_url) #uReq opens up a connection and grabs the page
page_html = uClient.read() #reads the html code for the page and stores it in a variable called "page_html"
uClient.close() #closes the connection to save resources

driver = webdriver.Chrome("C:/Users/user/Downloads/chromedriver") #opens up chrome driver, replace with your own path to chromedriver if needed

driver.get(my_url) #navigates to my_url

content = driver.page_source #gets html from current page that is open in chrome driver

soup1 = BeautifulSoup(content) #creates a beautiful soup object from html on current page open in chrome driver

for a in soup1.findAll('a',href=True, attrs={'class':'Zhf2z-'}): #finds all links with class "Zhf2z-" which are product links on flipkart search results pages, you can inspect element on any of these pages to find this out yourself or change this line of code according to your needs
name=a['title'] #extracts product name from title attribute of link tag <a> which is class "Zhf2z-"
price=a['aria-label'] #extracts product price from aria-label attribute of link tag <a> which is class "Zhf2z-"
products[name]=price #adds extracted data into dictionary called products with key as product name and value as product price

df = pd.DataFrame(list(products.items()),columns = ['Product Name','Product Price']) ##converts dictionary into dataframe for easy manipulation

df['Product Price']=[x[1:] for x in df['Product Price']] ##removes Rs sign from beginning of prices using list comprehension

df['Product Price']=[x[:-3] for x in df['Product Price']] ##removes , from prices using list comprehension

print (df) ##prints final dataframe containing all extracted data `enter code here` `enter code here` `enter code here` `enter code here` `enter code here` `enter code here` `enter code here` `enter code here` enter image description here`` enter image description here`` enter image description here`` enter image description her`` enter image description her`` enter image description her`` enter image description he `` enter image description he `` enter image description he `` Enter text after clickin`````````````````````````````````````````````.click() button on pagination at bottom right side of search results page (refer screenshot 2). This will load more products into view (refer screenshot 3). You can repeat above steps till you reach last page by changing number at end of url in my_url variable accordingly i.e., if you want to scrape second last page then change my_url='https://www.flipkart.com/search?q=iphone&amp;otracker=search&amp;otracker1=search&amp;marketplace=FLIPKART&amp;as-show=on&amp;as=off&amp;page='+str(totalPages-1) where totalPages is total number of pages that show up when you scroll down till end on any search results page (refer screenshot 4). You can find out total number of pages programmatically by inspecting element or manually like this - when you scroll down till end, count number of pagination buttons that show up at bottom right side (there are 40 buttons corresponding to 40 pages so if there are n buttons then there are n pages). Hope this helps! 🙂 Screenshot 1: Screenshot 2: Screenshot 3: Screenshot 4: <code>Enter text after clicking .click() button on pagination at bottom right side of search results page (refer screenshot 2). This will load more products into view (refer screenshot 3). You can repeat above steps till you reach last page by changing number at end of url in my_url variable accordingly i.e., if you want to scrape second last page then change my_url='https://www.flipkart.com/search?q=iphone&amp;otracker=search&amp;otracker1=search&amp;marketplace=FLIPKART&amp;as-show</code>=on&amp;as=off&amp;page='+str(totalPages-1) where totalPages is total number of pages that show up when you scroll down till end on any search results page (refer screenshot 4). You can find out total number of pages programmatically by inspecting element or manually like this - when you scroll down till end, count number of pagination buttons that show up at bottom right side (there are 40 buttons corresponding to 40 pages so if there are n buttons then there are n pages). Hope this helps! 🙂 Screenshot 1: Screenshot 2: Screenshot 3: Screenshot 4:

Tämä koodi yrittää kaapata useita sivuja verkkosivustolta Flipkart.com. Ensimmäinen rivi tuo seleeniverkkoohjaimen, jonka avulla voit automatisoida verkkosivuston tehtäviä. Toinen rivi tuo BeautifulSoupin, joka on Python-kirjasto HTML- ja XML-dokumenttien jäsentämiseen. Kolmas rivi tuo pandat, joka on Python-kirjasto tietojen analysointiin.

Seuraava koodilohko avaa yhteyden Flipkart-verkkosivustoon ja nappaa sivun HTML-koodin. Sitten se jäsentää HTML-koodin BeautifulSoupin avulla ja purkaa kaikki linkit luokassa "Zhf2z-". Nämä linkit vastaavat Flipkart-verkkosivustolla olevia tuotteita. Jokaisen linkin kohdalla se poimii tuotteen nimen ja hinnan vastaavasti otsikon ja aria-tunnisteen määritteistä. Sitten se lisää nämä tiedot sanakirjaan, jonka nimi on tuotteet. Tuotteen nimi on avaimena ja tuotteen hinta arvona.

Lopuksi se muuntaa sanakirjan pandastietokehykseksi (df) helpottamaan käsittelyä. Se poistaa Rs-merkin kaikista hinnoista ja poistaa myös pilkut kaikista hinnoista. Sitten se tulostaa lopullisen datakehyksen, joka sisältää kaikki poimitut tiedot.

kaavinta

Pythonissa kaapiminen on prosessi, jossa tietoja poimitaan verkkosivulta tai asiakirjasta komentosarjan avulla. Kaapiminen voidaan tehdä manuaalisesti verkkoselaimella tai se voidaan tehdä Python-skriptillä.

Parhaat kaavinet

Pythonissa on monia kaapimia, mutta joitain parhaista niistä ovat:

1. scrapy
2. Kaunis keitto
3. pyynnöt
4. matplotlib

Seleeni

Selenium on web-selaimen automaatiotyökalu. Sitä voidaan käyttää automatisoimaan tehtäviä, kuten verkkosivustojen testaamista, kuvakaappausten ottamista ja käyttäjien vuorovaikutusten kirjaamista. Seleeniä voidaan käyttää myös testiskriptien luomiseen ja automaattisten testien suorittamiseen.

Related viestiä: