【问题标题】:f.write keeps returning "NameError: name 'productre_time' is not defined"f.write 不断返回“NameError:名称'productre_time'未定义”
【发布时间】: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


【解决方案1】:

您面临的问题是,如果您无法从汤对象中检索值,那么该变量将不会被初始化。因此,您之前已经用空字符串初始化了所有变量

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 = ""
        product_name = container.select_one("div div:nth-of-type(2)").span.text
    except AttributeError:
        print(0)
    else:
        print(product_name)

    try:
        bednbath = ""
        bednbath = container.select_one("div div:nth-of-type(2)").div.div.text
    except AttributeError:
        print(0)
    else:
        print(bednbath)

    try:
        product_location = ""
        location_container = container.findAll("div", {"class": "description--2-ez3"})
        product_location = location_container[0].text
    except AttributeError:
        print(0)
    else:
        print(product_location)

    try:
        product_price = ""
        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:
        productre_time = ""
        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()

输出:

1yr very nice 2bedrooms flat for rent@West Hills Mall
Beds: 2, Baths: 2
Accra, Apartments
GH₵ 650 /month
0
Land for sale at East Legon Hills
100/70 acre
Accra, Land
GH₵ 100,000
0
Locomotive new 2bedrm spintex
Beds: 2, Baths: 1
Accra, Houses
GH₵ 1,200 /month
1 minute
For sale,9bedrooms house @East Legon
Beds: 9, Baths: 10
Accra, Houses
GH₵ 8,820,000
1 minute
AN EXECUTIVE NEWLY BUILT CHAMBER AND HALL FOR@SPINTEX
Beds: 2, Baths: 2
Accra, Apartments
GH₵ 800 /month
2 minutes
AN EXECUTIVE NEWLY BUILT 2BEDROOM 2WASHROOM FOR RENT@SPINTEX
Beds: 2, Baths: 2
Accra, Apartments
GH₵ 1,000 /month
2 minutes
AN EXECUTIVE CHAMBER AND HALL APARTMENT FOR@SPINTEX
Beds: 2, Baths: 1
Accra, Apartments
GH₵ 500 /month
3 minutes
REGISTERED 5 BRM HOUSE AT KOKROKO MALLAM
Beds: 5, Baths: 3
Accra, Houses
GH₵ 400,000
4 minutes
SHOP WITH WASHROOM AT ARKO ADJEI PARK, OSU
15 x 15 sqft
Accra, Commercial Property
GH₵ 1,000 /month
7 minutes
Sophisticated new 3bedrm HOUSE spintex
Beds: 3, Baths: 4
Accra, Houses
GH₵ 2,000 /month
7 minutes
NEW & EXECUTIVE 2 MASTER BEDROOM APARTMENT NEAR MAINROAD, TETEGU
Beds: 2, Baths: 3
Accra, Apartments
GH₵ 1,800 /month
7 minutes
nice ordinary single room at Agege 205

Accra, Rooms
GH₵ 100 /month
23 minutes
executive 4bed house for sale at kasoa cp
Beds: 4, Baths: 3
Accra, Houses
GH₵ 280,000
26 minutes
nice 3bed self compound @south odorko
Beds: 3, Baths: 2
Accra, Houses
GH₵ 1,300 /month
31 minutes
2bedroom At Abelemkpe. 1year
Beds: 2, Baths: 1
Accra, Apartments
GH₵ 700 /month
34 minutes
5 Bedroom house for rent BOTWE
Beds: 4, Baths: 6
Accra, Houses
GH₵ 12,000 /month
39 minutes
Three bedrooms self compound house for sale at Odorkor
Beds: 3, Baths: 3
Accra, Houses
GH₵ 1,540,000
1 hour
Genuine Lands with land Title/land Deeds
100 acre
Greater Accra, Land
GH₵ 25,000
1 hour
4 bedroom self compound for rent in north dzorwulu
Beds: 4, Baths: 4
Accra, Houses
GH₵ 3,000 /month
1 hour
2 Bedrooms & A Hall For Rent Ntankoful
Beds: 2, Baths: 1
Sekondi Takoradi, Apartments
GH₵ 450 /month
1 hour
2 bedroom apartment for rent at Tse Addo Teshie Manet
Beds: 2, Baths: 3
Accra, Apartments
GH₵ 2,000 /month
1 hour
2 bedroom apartments at Madina Adenta Oyarifa
Beds: 2, Baths: 2
Accra, Apartments
GH₵ 1,300 /month
1 hour
Airport 5 Bedrooms Mansion For Rent
Beds: 5, Baths: 5
Accra, Houses
GH₵ 18,560 /month
1 hour
East Legon 4 Bedrooms House With Swiming Pool For Sale
Beds: 4, Baths: 4
Accra, Houses
GH₵ 3,770,000
1 hour
Airport 5 Bedrooms House With Swiming Pool
Beds: 5, Baths: 5
Accra, Houses
GH₵ 29,000 /month
1 hour
Newly executive 3bedroom self contain for sale at oyarifa Ghana flag
Beds: 3, Baths: 2
Greater Accra, Houses
GH₵ 350,000
1 hour
3bedroom house 4sale @Adenta
Beds: 3, Baths: 4
Accra, Houses
GH₵ 650,000
1 hour

【讨论】:

  • 我运行你的代码并得到这个错误;回溯(最后一次调用):文件“C:/Users/m/PycharmProjects/RealEstate Project/Extra.py”,第 62 行,在 f.write(product_name.replace(",", "|") + "," + bednbath + "," + product_location + "," + product_price + "," + productre_time + "\n") 文件 "C:\Users\m\AppData\Local\Programs\Python\Python38\lib \encodings\cp1252.py",第 19 行,编码返回 codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u20b5' in position 74: character maps到
  • 你能给出发生这种情况的网址吗?
  • 你是在python2还是python3中运行?
  • 在python 3中运行脚本
  • 我在 python 3.8.3 中运行脚本
猜你喜欢
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 2021-04-15
  • 2019-01-26
  • 2021-10-05
  • 2017-08-16
  • 2019-08-18
相关资源
最近更新 更多