首页 > 解决方案 > 将响应转换为 .csv 文件格式时如何修复 Nan Error

问题描述

我正在执行网络抓取任务,我需要将其保存在 csv 文件中。我已经完成了所有工作,需要将其输出到 csv 文件,但我得到Nan的是文件中的值。

我注意到该错误与代码的后续路径有关,但我不知道究竟是什么问题以及它是什么。

显示错误的图像

蟒蛇代码

import requests, json, re, csv
from bs4 import BeautifulSoup
import pandas as pd

city = input("Enter your city: ")
url = "https://www.zomato.com/" + city + "/top-restaurants"
header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36"}
response = requests.get(url, headers=header)

html = response.text
soup = BeautifulSoup(html, "html.parser")
print(soup.title.text)
    
restaurants = []
address = []
cuisine = []
ratings_black = []
ratings_red = []

top_rest = soup.find("div", class_="bke1zw-0 cMipmx")
restaurant_divs = top_rest.select("div > section > div")

for rdiv in restaurant_divs:
    name = rdiv.find("a", recursive=False).text.strip()
    rating_div, address_div, cuisine_div = rdiv.find_all("div", recursive=False)
    ratings = re.findall(r"([\d\.]+)\(([\d,]+)\)", rating_div.text)
    black_rating = (float(ratings[0][0]), int(ratings[0][1].replace(',', ''))) if ratings else (None, None)
    red_rating = (float(ratings[1][0]), int(ratings[1][1].replace(',', ''))) if len(ratings) > 1 else (None, None)

    restaurants.append(name)
    address.append(address_div.text)
    cuisine.append(cuisine_div.text)
    ratings_black.append(black_rating)
    rating_red.append(red_rating)

header = ["Restaurants", "Black Ratings", "Red Ratings", "Address", "Cuisine"]
indices = [i for i in range(1, len(restaurants) + 1)]
all_rests = zip(restaurants, ratings_black, ratings_red, address, cuisine)
dt = pd.DataFrame(list(all_rests), index=indices, columns=header)
dt.to_csv("Top restaurants in " + city + ".csv")
print(dt)

标签: pythonpandascsv

解决方案


推荐阅读