亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么soup.find('title') 在BeautifulSoup 中什么都不返回?

為什么soup.find('title') 在BeautifulSoup 中什么都不返回?

收到一只叮咚 2021-08-05 16:49:59
我正在使用 requests 和 beautifulsoup 來解析 url 的響應內容。但是當我嘗試解析響應并soup.find('title') 在 Beautifulsoup 中找到標題時,它沒有返回任何內容。甚至沒有錯誤。它只是什么都不做。上面的打印語句soup.find() 正在執行。但不是 if 和 if 之后的那個。import requests, osfrom bs4 import BeautifulSouplis=[    'https://oxhp-member-elr.uhc.com/Member/MemberPortal/'    ]for element in lis:    resp = requests.get(element)    if resp.status_code == 200:        cont = resp.content.decode('UTF-8')        try:            soup = BeautifulSoup(cont, "html.parser")            print('Now')            if soup.findAll('title')[0].get_text() is None:                print('Hi')            print('after if')            print(element.ljust(element_length), resp.status_code, soup.find('title').text)        except:            pass我soup.find('title').text也試過' 。但這也不起作用。任何人都可以讓我知道我的代碼有什么問題嗎?
查看完整描述

1 回答

?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

您正在使用 try 塊處理異常并且什么都不做(只是pass),這就是您沒有看到錯誤消息的原因。如果發生不在 try 塊內的錯誤,默認行為是中斷代碼并打印堆棧跟蹤。如果在 try 塊內發生錯誤,代碼將跳轉到 except 塊,接下來發生什么由您決定。不會自動打印錯誤信息。


如果您嘗試打印錯誤或在循環內添加 Soup 對象的打印語句,您將看到以下內容:


    try:

        soup = BeautifulSoup(cont, "html.parser")

        print('Now')


        # Print the soup object

        print(soup)

        if soup.findAll('title')[0].get_text() is None:

            print('Hi')

        print('after if')

        #print(element.ljust(element_length), resp.status_code, soup.find('title').text)

    except Exception as error:

        # Handle the exception with some information.

        print(error)

        pass

給出輸出


Sorry, we are unable to process your request at this time.

對于打印語句,錯誤消息如下所示:


list index out of range

基本上,您無法解析 URL,因此您嘗試使用[0]if 語句中的訪問空數組,這會引發錯誤。


查看完整回答
反對 回復 2021-08-05
  • 1 回答
  • 0 關注
  • 384 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號