簡體   English   中英

當我在if語句中嘗試使用列表索引時,為什么會失敗?

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

當我嘗試在語句中建立索引時,它表示索引超出范圍。 我正在嘗試從網站上抓取東西。

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])

代碼返回一個錯誤,指出list index out of range並指向for循環中的stuff[0]

添加一個步驟來檢查元組是否為空。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM