无法在python中保存csv文件中的记录



不将75条记录保存在csv文件中,但在终端上打印记录网站:https://sehat.com.pk/categories/Over-The-Counter-Drugs/Diarrhea-and-Vomiting-/?sort=alphaasc&页面= 2

import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
for page_number in range(1, 6):
url = f'https://sehat.com.pk/categories/Over-The-Counter-Drugs/Diarrhea-and-Vomiting-/?sort=featured&page='+str(page_number)
r = requests.get(url)
#time.sleep(6)
soup = BeautifulSoup(r.content, 'html.parser')
content = soup.find_all('div', class_ = 'col-md-12 pr-0 pl-0')
suit =[]
for property in content:

names = property.find('div',class_='col-md-12 d-table-cell align-middle')
name= names.find('img', class_ = 'img-fluid')['alt']
links=property.find('a')['href']
try:
price= property.find('div', class_ = 'ProductPriceRating d-table-cell text-center pl-1 pr-1 align-middle').text.strip()
except AttributeError:
price=''
try:
product_brand =property.find('div',class_ ='ProductBoxProductBrand-div d-table-row text-center pl-1 pr-1 align-middle').text.strip()
except AttributeError:
product_brand=''
print(name,product_brand,links,price)
fabric = {
'productname':name,
'product_Brand':product_brand,
'Product_price': price,
'links': links,
}    
suit.append(fabric)
print ("Importing to Data into CSV File...!!")
df = pd.DataFrame(suit)
print("Saved Sucessfully....")
df.to_csv('Diarrhea_and_Vomiting_pagination.csv', index=False)

通过在for循环中创建变量suit=[],您将覆盖每个循环中的现有数据。

你需要在for循环前声明suit变量

...
suit=[]
for page_number in range(1, 6):
...

相关内容

  • 没有找到相关文章

最新更新