Python 美化组索引器:列表索引超出范围?

Python 美化组索引器:列表索引超出范围?,python,python-3.x,indexing,beautifulsoup,Python,Python 3.x,Indexing,Beautifulsoup,我得到的错误是: Traceback (most recent call last): File "e:\AMAN\Projects\Python\CoronaVirus Outbreak Notification System\main2.py", line 28, in <module> for tr in soup.find_all('tbody')[1].find_all('tr'): IndexError: list index out of

我得到的错误是:

Traceback (most recent call last):
  File "e:\AMAN\Projects\Python\CoronaVirus Outbreak Notification System\main2.py", line 28, in <module>
    for tr in soup.find_all('tbody')[1].find_all('tr'):
IndexError: list index out of range

出现此错误是因为
soup.find_all('tbody')
没有索引1。时间不够长。如果您的代码有时只有那个索引,那么您可以使用

try: 
  soup.find_all('tbody')[1]
except IndexError:
  # Do whatever
Tbody有时给出不明确的结果,因此,最终,一些XPath被识别为“表”


导致此问题的原因是您无法索引
汤。使用
[1]
查找所有('tbody')[1]
,这将导致索引器,因为不存在[1]。检查
汤中到底有什么。查找所有('tbody')
并确保在索引之前有要索引的内容。或者,如果有时代码可以被索引,则使用Try/Except捕捉错误。
try: 
  soup.find_all('tbody')[1]
except IndexError:
  # Do whatever
from plyer import notification
import requests
from bs4 import BeautifulSoup
import time

def notifyMe(title, message):
    notification.notify(
        title = title,
        message = message,
        app_icon = "icon.ico",
        timeout = 6
    )


def getData(url):
    r = requests.get(url)
    return r.text


if __name__ == "__main__":
    while True:
        # notifyMe("Harry", "Lets stop the spread of this virus together")
        myHtmlData = getData('https://www.mohfw.gov.in/')
    soup = BeautifulSoup(myHtmlData, 'html.parser')
    # print(soup.prettify())
    myDataStr = ""
    for tr in soup.find_all('table')[1].find_all('tr'):  #try " table "
        myDataStr += tr.get_text()
    myDataStr = myDataStr[1:]
    itemList = myDataStr.split("\n\n")

    states = ['Chandigarh', 'Telengana', 'Uttar Pradesh']
    for item in itemList[0:22]:
        dataList = item.split('\n')
        if dataList[1] in states: 
            nTitle = 'Cases of Covid-19'
            nText = f"State {dataList[1]}\nIndian : {dataList[2]} & Foreign : {dataList[3]}\nCured :  {dataList[4]}\nDeaths :  {dataList[5]}"
            notifyMe(nTitle, nText)
            time.sleep(2)
    time.sleep(3600)