Python wie löse 'NoneType' object is not subscriptable?

Hallo!

Ich schreibe ein kleines Pythonprogramm, das als Web Crawler fungieren soll.Leider erhalte ich in Zeile 36 ein Fehler:

  brand = make_rating_sp[0].img["title"].title()
TypeError: 'NoneType' object is not subscriptable

Leider, finde ich keine Lösung. Wie könnte ich diesen Fehler lösen? Danke im Voraus!

make_rating_sp[0].img is None.

from bs4 import BeautifulSoup as soup  # HTML data structure
from urllib.request import urlopen as uReq  # Web client

# URl to web scrap from.
# in this example we web scrap graphics cards from Newegg.com
page_url = "http://www.newegg.com/Product/ProductList.aspx?Submit=ENE&N=-1&IsNodeId=1&Description=GTX&bop=And&Page=1&PageSize=36&order=BESTMATCH"

# opens the connection and downloads html page from url
uClient = uReq(page_url)

# parses html into a soup data structure to traverse html
# as if it were a json data type.
page_soup = soup(uClient.read(), "html.parser")
uClient.close()

# finds each product from the store page
containers = page_soup.findAll("div", {"class": "item-container"})

# name the output file to write to local disk
out_filename = "graphics_cards.csv"
# header of csv file to be written
headers = "brand,product_name,shipping \n"

# opens file, and writes headers
f = open(out_filename, "w")
f.write(headers)

# loops over each product and grabs attributes about
# each product
for container in containers:
    # Finds all link tags "a" from within the first div.
    make_rating_sp = container.div.select("a")

    # Grabs the title from the image title attribute
    # Then does proper casing using .title()
    brand = make_rating_sp[0].img["title"].title()

    # Grabs the text within the second "(a)" tag from within
    # the list of queries.
    product_name = container.div.select("a")[2].text

    # Grabs the product shipping information by searching
    # all lists with the class "price-ship".
    # Then cleans the text of white space with strip()
    # Cleans the strip of "Shipping $" if it exists to just get number
    shipping = container.findAll("li", {"class": "price-ship"})[0].text.strip().replace("$", "").replace(" Shipping", "")

    # prints the dataset to console
    print("brand: " + brand + "\n")
    print("product_name: " + product_name + "\n")
    print("shipping: " + shipping + "\n")

    # writes the dataset to file
    f.write(brand + ", " + product_name.replace(",", "|") + ", " + shipping + "\n")

f.close()  # Close the file
programmieren, Informatik, Python, Python 3
Pygame hängt sich bei while True: loop auf?

Hallo,

ich programmiere gerade ein Spiel in Pygame. Auf jeden Fall möchte ich den Ninja Wurfsternen (&anderen Waffen)Ammo geben, dass man eine bestimmte Anzahl von diesen hat und diese nicht spammen kann. Wenn man Space drückt, wird der Ammo Variable eins abgezogen und wenn der Ammo (heißt es der Ammo? ) höher als 0 ist, wird der Befehl self.shoot() ausgeführt. Jetzt mein Problem: Egal, welche Nummer die Variable hat (außer Null), kann ich einmal schießen und danach nicht mehr, auch wenn ich Space drücke. Ich weiß nur nicht wieso. Wenn ich es in einen while True, loop packe, hängt sich pygame auf. Nur wie kann ich das fixen, dass ich öfter als 1 Mal schießen kann. Hier mein benötigter Code (ohne den While True loop):

class Player(pg.sprite.Sprite):

def __init__(self, game, x, y):

self.weapon = 'blowpipe'

self.shurikan = False

self.blowpipe = False

self.xp = PLAYER_XP

self.shoot_ammo = True

self.BLOWPIPE_AMMO = 5

self.SHURIKAN_AMMO = 5

def get_keys(self):

keys = pg.key.get_pressed()

if keys[pg.K_SPACE]:

if self.weapon == 'blowpipe' and self.shoot_ammo == True:

self.BLOWPIPE_AMMO -= 1

if self.BLOWPIPE_AMMO < 0:

self.BLOWPIPE_AMMO = 0

if self.BLOWPIPE_AMMO == 0:

self.shoot_ammo = False

if self.BLOWPIPE_AMMO > 0:

self.shoot()

if self.weapon == 'shurikan' and self.shoot_ammo == True:

self.SHURIKAN_AMMO -= 1

if self.SHURIKAN_AMMO < 0:

self.SHURIKAN_AMMO = 0

if self.SHURIKAN_AMMO == 0:

self.shoot_ammo = False

if self.SHURIKAN_AMMO > 0:

self.shoot()

def shoot(self):

if self.shoot_ammo == True:

now = pg.time.get_ticks()

if now - self.last_shot > WEAPONS[self.weapon]['rate']:

self.last_shot = now

dir = vec(1, 0).rotate(-self.rot)

EinegleicheListegibtesfürBlowpipe.

pos = self.pos + BARREL_OFFSET.rotate(-self.rot)

self.vel = vec(-WEAPONS[self.weapon]['rate'], 0).rotate(-self.rot)

for i in range(WEAPONS[self.weapon]['count']):

spread = uniform(-WEAPONS[self.weapon]['spread'], WEAPONS[self.weapon]['spread'])

Blowpipe(self.game, pos, dir.rotate(spread))

Außerdem gibt es eine Weapons Liste in einem anderen File:

WEAPONS['blowpipe'] = {'img': 'blowpipe.png',

'speed': 500,

'lifetime': 600,

'rate': 300,

'kickback': 0,

'spread': 5,

'damage': 3,

'size': 'blowpipe',

'count': 1}

Eine ähnliche Liste benutze ich für den Shurikan. Thx

Computer, Mac, programmieren, Informatik, Python, Python 3, Pygame, VS Code
Python function wird zweimal aufgerufen?

Guten Morgen,

Ich habe ein problem mit meinem skript. Ich möchte gerne, dass wenn man einen kliptaster betätigt dieser in einem array gespeichert wird. Leider wird die Zahl des Tasters doppelt im array angezeigt. Er ruft bei mir die function zweimal auf.

import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
import time
import sys, traceback
 
#https://raspberrypihq.com/use-a-push-button-with-raspberry-pi-gpio/
 
tastenSeq=[]
 
 
def button_callback(channel):
       print("Taster 2: AN")
       GPIO.output(12,True)
       tastenSeq.append(2)
       time.sleep(1.0)
       GPIO.output(12,False)
       print("Taster 2: AUS")
 
 
def button_callback2(channel2):
       print("Taster 5: AN")
       GPIO.output(32,True)
       tastenSeq.append(5)
       time.sleep(1.0)
       GPIO.output(32,False)
       print("Taster 5: AUS")
       print tastenSeq
 
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12,GPIO.OUT)
GPIO.setup(32,GPIO.OUT)
 
GPIO.setwarnings(False) # Ignore warning for now
#GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
 
GPIO.setup(31, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 10 to be an input pin and set initial value to be pulled low (off)
GPIO.add_event_detect(31,GPIO.RISING,button_callback) # Setup event on pin 10 rising edge
 
 
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 10 to be an input p$
GPIO.add_event_detect(15,GPIO.RISING,callback=button_callback2) # Setup event on p$
 
message = input("Press enter to quit\n\n") # Run until someone presses enter
GPIO.cleanup() # Clean up

 

 

Bild zum Beitrag
Computer, Computerspiele, programmieren, Informatik, Python 3, Raspberry Pi, Raspberry, Raspberry Pi 3

Meistgelesene Fragen zum Thema Python 3