
Основният проблем при изтриването на множество страници с помощта на Selenium в Python е, че може да отнеме много време и да получите желаните резултати.
Опитвам се да изстържа няколко страници с помощта на селен в Python. Опитах следния код, но той изтрива само първата страница. Как мога да го накарам да изстърже всички страници?
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&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off&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&otracker=search&otracker1=search&marketplace=FLIPKART&as-show</code>=on&as=off&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:
Този код се опитва да изтрие множество страници на уебсайта Flipkart.com. Първият ред импортира selenium webdriver, който ви позволява да автоматизирате задачи на уебсайт. Вторият ред импортира BeautifulSoup, която е библиотека на Python за анализиране на HTML и XML документи. Третият ред импортира pandas, което е библиотека на Python за анализ на данни.
Следващият блок от код отваря връзка към уебсайта на Flipkart и грабва HTML кода за страницата. След това анализира HTML кода с помощта на BeautifulSoup и извлича всички връзки с класа „Zhf2z-“. Тези връзки съответстват на продукти на уебсайта на Flipkart. За всяка връзка той извлича името на продукта и цената съответно от атрибутите заглавие и ария-етикет. След това добавя тези данни към речник, наречен продукти, с името на продукта като ключ и цената на продукта като стойност.
И накрая, той преобразува речника в рамка от данни на pandas (df) за лесно манипулиране. Той премахва знака Rs от всички цени и също така премахва запетаите от всички цени. След това отпечатва окончателния кадър с данни, съдържащ всички извлечени данни.
Извличане
В Python скрейпингът е процес на извличане на данни от уеб страница или документ с помощта на скрипт. Изтриването може да се извърши ръчно с помощта на уеб браузър или може да се направи с помощта на скрипт на Python.
Най-добрите стъргалки
В Python има много скрепери, но някои от най-добрите включват:
1. остъргвам
2. Красива супа
3. молби
4. matplotlib
Селен
Selenium е инструмент за автоматизация на уеб браузър. Може да се използва за автоматизиране на задачи като тестване на уебсайтове, заснемане на екранни снимки и регистриране на потребителски взаимодействия. Selenium може да се използва и за създаване на тестови скриптове и извършване на автоматизирани тестове.