简体   繁体   English

当我在if语句中尝试使用列表索引时,为什么会失败?

[英]When I try to use list indexing in my if statement, why does it fail?

When I try to index in the statement, it says index out of range. 当我尝试在语句中建立索引时,它表示索引超出范围。 I am trying to scrape stuff from the website. 我正在尝试从网站上抓取东西。

import requests
from bs4 import BeautifulSoup

page = requests.get('https://www.set.or.th/set/factsheet.do?symbol=TRUE&ssoPageId=3&language=en&country=US')
soup = BeautifulSoup(page.text, 'html.parser')

list_stuff = list()
for x in soup.findAll('table',{'class':'factsheet'}):
   for tr in x.findAll('tr'):
      stuff=[td for td in tr.stripped_strings]
         if stuff[0] == 'Beta':
            list_stuff.append(stuff[1])

The code returns an error saying list index out of range and points to the stuff[0] line in the for loop 代码返回一个错误,指出list index out of range并指向for循环中的stuff[0]

Add a step to check if the tuple is empty or not. 添加一个步骤来检查元组是否为空。

if not not stuff:                     #check if stuff is not empty
    if stuff[0] == 'Beta':
        list_stuff.append(stuff[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当我尝试使用 corsheaders 时,为什么我的应用程序会中断? - Why does my application break when I try to use corsheaders? 当我从目录外部导入此函数时,为什么我的python import语句失败? - Why does my python import statement fail when I import this function from outside the directory? 当我尝试使用 OOP 和类时,为什么我的代码在 python 中显示 NameError? - Why does my code show NameError in python when I try to use of OOP and classes? 尝试打印列表内容时,为什么要打印索引? - Why is my index printing when I try to print the contents of the list? 为什么我的if语句说两个字符串不在列表中? - Why does my if statement say that two strings are in a list when its not? Theano:为什么索引会在这种情况下失败? - Theano: Why does indexing fail in this case? 为什么我的程序会产生列表索引问题? - Why does my program generate a list indexing issue? 为什么在调用完全执行此操作的函数时必须重做 try-except 语句? - Why do I have to redo a try-except statement when calling a function that does this exactly? 为什么我的 try 语句不断重复自己? - Why does my try statement keep repeating itself? 当我尝试分配给一个列表时,为什么每个列表值都会改变? - Why does every list value change when I try to assign to one list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM