簡體   English   中英

Python 用字符串替換列表中的空列表以避免 IndexError: list index out of range

[英]Python replacing empty list in a list with a string to avoid IndexError: list index out of range

我編寫了這段代碼,它可以很好地從網站列表中抓取 H1 標簽。 有一些特定的網站沒有 H1,因此返回一個空列表並給出 IndexError: list index out of range,並停止腳本。

    list_flagged = df['Websites'].to_list()

    new_flagged_list = []

    for site in list_flagged:                                                                
        quote_page = requests.get(site, headers=random_header)
        soup = BeautifulSoup(quote_page.text, 'html.parser')
        h1tag = soup.find_all('h1')
        titles = [(h1.get_text()).strip() for h1 in h1tag] 
        appended = new_flagged_list.append(titles)
        print('appended')
        if new_flagged_list == ['']:
            ['x']    
        new = [x[0] for x in new_flagged_list]

我嘗試使用 if new_flagged_list == ['']: 更改空行,但仍然出現錯誤。 反正我不明白為什么

    new = [x[0] for x in new_flagged_list]

忽略列表索引錯誤的列表中的空列表。 為什么它不能保留一個空列表?

如何使用任何字符串更改列表中的空列表以避免錯誤?

謝謝!

您可以使用

if not new_flagged_list:
       print("do task here")

在上面的代碼中,您正在檢查列表是否為空

我不明白你想做什么

if new_flagged_list == ['']:
            ['x']  

您在這里沒有為變量分配任何東西。 你也可以試試:

if titles:
    appended = new_flagged_list.append(titles)

這樣當標題不為空時,您只有 append 。

這些行:

        if new_flagged_list == ['']:
            ['x'] 

除了創建並立即銷毀僅包含“x”的列表之外,不要做任何事情。 我猜你想要:

new_flagged_list = ['x']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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