【发布时间】:2021-12-11 11:48:36
【问题描述】:
当我运行代码时,它会从网站打印数据,但问题是,我在代码中使用了自动滚动功能,它可以工作,但不能滚动到网站的最后一页,这样,我在 CSV 文件中仅获得 122 条记录,但在网站中,直到网站的最后一页为止有很多记录,所以请帮帮我。
import time
import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
from selenium import webdriver
url ='https://dawaai.pk/medicine-category/alimentary-tract-metabolism-2'
driver = webdriver.Chrome('E:/chromedriver')
driver.get(url)
SCROLL_PAUSE_TIME = 1
#time.sleep(4)
# Get scroll height
"""last_height = driver.execute_script("return document.body.scrollHeight")
this doesn't work due to floating web elements on youtube
"""
last_height = driver.execute_script("return document.documentElement.scrollHeight")
conte = None
while True:
# Scroll down to bottom
driver.execute_script("window.scrollTo(0,document.documentElement.scrollHeight);")
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.documentElement.scrollHeight")
if new_height == last_height and conte:
print("break")
break
last_height = new_height
#time.sleep(5)
pageSource = driver.page_source
soup = BeautifulSoup(pageSource, 'html.parser')
aaa = soup.find('div',class_='columns systemic-products-div')
conte= aaa.find_all('div',class_='column col-3 mb-20')
#print(conte)
suit = []
for items in conte:
product_title = items.find("h2").text.strip()
product_Brand_Name = items.find("p").text.strip()
# title=''
print(len(product_title))
#driver.close()
fabric = {
'productname':product_title,
'Product_Brand_Name':product_Brand_Name
}
suit.append(fabric)
print ("Importing to Data into CSV File...!!")
df = pd.DataFrame(suit)
print("Saved Sucessfully....")
df.to_csv('dawaii.csv', index=False)
【问题讨论】:
标签: python pandas beautifulsoup request webdriver