python - 将响应转换为 .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)
解决方案
推荐阅读
- curl - SLURM:卷曲的作业无缘无故地取消了 2 卷曲 [JobState=CANCELLED 原因=无 ExitCode=0:15]
- pine-script - 如何在“过去 14 根蜡烛的时期/如何定义过去 14 根蜡烛的范围或时期?”中检查条件是真还是假?
- c++ - 怎么了?尽管#define _USE_MATH_DEFINES 和#include,M_PI 未声明错误
- java - Tomcat 9 上的 SSL Windows 认证错误
- java - 集成 Admob 的“App Open Ad”后的 IllegalStateException
- gpgpu - 使用 PGP 公钥生成指纹
- git - 在多个 Gît 存储库上同步多个 PR
- intersystems-iris - 将 IRIS 数据库拆分到多个驱动器
- matlab - 使用 matlab 的 ODE45 和 Runge-Kutta 方法对电晕进行优化控制
- java - 如果我在代码中将其与隐式等待一起使用,则显式等待不起作用