网页无限滚动时出现网页抓取问题

时间:2019-05-16 14:07:57

标签: python selenium-webdriver web-scraping

我必须抓取一个电子商务网站,该网站在第一页上加载了45种产品,然后在滚动到页面末尾时又加载了另外45种产品。

我正在使用Python Selenium Web驱动程序抓取此页面。

Ajax似乎在每次重新加载时都替换了容器,因此在加载所有产品之后无法提取所有数据。

为您的参考附加代码。请指导我如何刮擦所有产品

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import pandas
from numpy import long

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome()
html=driver.get("https://www.ajio.com/women-jackets-coats/c/830316012")
assert 'Ajio' in driver.title
content = driver.find_elements_by_class_name('item')
totalitems=long(driver.find_element_by_class_name('length').text.strip(' Items Found').replace(',','',10))

loop_count=int(((totalitems-len(content))/len(content)))

print(loop_count)

data=[]
row=['Brand','Description','Offer_Price','Original_Price','Discount']
data.append(row)

for i in range(1,loop_count):
    content = driver.find_elements_by_class_name('item') 
    print(i)
    print(len(content))

    for item in content:
        row=[]
        row.append(item.find_element_by_class_name('brand').text.strip())
        row.append(item.find_element_by_class_name('name').text.strip())
        row.append(item.find_element_by_class_name('price').text.strip().strip('Rs. '))
        try:
            row.append(item.find_element_by_class_name('orginal-price').text.strip('Rs. '))
        except NoSuchElementException as exception:
            row.append(item.find_element_by_class_name('price').text.strip('Rs. '))

        try:
            row.append(item.find_element_by_class_name('discount').text.strip())
        except NoSuchElementException as exception:
            row.append("No Discount")

        data.append(row)
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight-850);")
    try:
        myElem = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.CLASS_NAME, 'loader')))
    except TimeoutException:
        print("Loading took too much time!")



df = pandas.DataFrame(data)
df.to_csv("C:\Ajio.csv", sep=',',index=False, header=False, mode='w')   #mode='a' for append

1 个答案:

答案 0 :(得分:1)

这听起来像是您遇到的问题是基于后续的重新加载/滚动所要抓取的数据不一致。

一种解决方案是存储比该函数的范围还大的数据结构,该数据结构将记录您到目前为止所看到的项目。在页面重新加载/滚动时,您可以检查数据结构中是否已存在每个项目,以及是否没有将其添加到数据结构中,直到您确保已点击页面上的所有可能项目。

祝你好运!