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

时间:2018-11-02 10:10:58

标签: python python-3.x python-2.7 beautifulsoup python-requests

我正在处理请求和beautifulsoup来解析URL的响应内容。

但是当我尝试解析响应并在Beautifulsoup中使用soup.find('title')查找标题时,它什么也没有返回。甚至没有错误。

它什么都不做。 soup.find()上方的打印语句正在执行。但不是if和after if内部的那个。

import requests, os
from bs4 import BeautifulSoup
lis=[
    '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 个答案:

答案 0 :(得分:0)

您正在使用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,因此尝试在if语句中使用[0]访问空数组,这将引发错误。