【发布时间】:2020-11-04 15:49:19
【问题描述】:
我正在尝试使用漂亮的汤来获取信息并将数据写入 csv 文件。到目前为止,代码运行良好,但是当我添加 f.write 时,我不断收到 NameError。我尝试重命名变量并使用缩进,但我仍然无法解决问题。我究竟做错了什么? (如果我能解决这个问题,这将是我的第一个程序,请多多包涵)
这是我的代码;
import requests
from bs4 import BeautifulSoup
url = 'https://tonaton.com/en/ads/ghana/property'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
containers = soup.findAll("div", {"class": "container--2uFyv"})
container = containers[0]
filename = "tonaton_data.csv"
f = open(filename, "w")
headers = "product_name, upload_time, bednbath, product_location, product_price\n"
f.write(headers)
for container in containers:
try:
product_name = container.select_one("div div:nth-of-type(2)").span.text
except AttributeError:
print(0)
else:
print(product_name)
try:
bednbath = container.select_one("div div:nth-of-type(2)").div.div.text
except AttributeError:
print(0)
else:
print(bednbath)
try:
location_container = container.findAll("div", {"class": "description--2-ez3"})
product_location = location_container[0].text
except AttributeError:
print(0)
else:
print(product_location)
try:
price_container = container.findAll("div", {"class": "price--3SnqI color--t0tGX"})
product_price = price_container[0].span.text
except AttributeError:
print(0)
else:
print(product_price)
try:
date_container = container.findAll("div", {"class": "updated-time--1DbCk"})
productre_time = date_container[0].text
except IndexError:
print(0)
else:
print(productre_time)
f.write(product_name.replace(",", "|") + "," + bednbath + "," + product_location + "," + product_price + "," + productre_time + "\n")
f.close()
错误;
Traceback (most recent call last):
File "C:/Users/mmu/PycharmProjects/RealEstate Project/Pofore_tonaton.py", line 59, in <module>
f.write(product_name.replace(",", "|") + "," + bednbath + "," + product_location + "," + product_price + "," + productre_time + "\n")
NameError: name 'productre_time' is not defined
【问题讨论】:
-
你能发布整个错误吗? @KeyserPython
-
仔细查看错误信息,然后查看代码。显然,错误是抱怨
productre_time没有得到定义。你认为productre_time的价值来自哪里?它来自productre_time = date_container[0].text,是吗?好的,现在我看到您已经考虑了IndexError由[0]引发的可能性。 如果发生这种情况,您希望名称productre_time会发生什么?你希望它无论如何都会被定义吗?为什么?有什么价值? -
@KarlKnechtel 我希望
product_time打印 0 或如果有IndexError则为空白。只有前两个产品没有productre_time类,但我还是想在那里打印一些东西,以便脚本运行没有问题 -
多注意我写的。当
IndexError出现时,您认为代码实际上会做什么?为什么? -
@KarlKnechtel 当
IndexError发生时,由于异常,我希望脚本为print(0)
标签: python csv file exception beautifulsoup