【问题标题】:Exception Handling in Beautiful soup/PythonBeautiful soup/Python 中的异常处理
【发布时间】:2016-08-02 12:19:45
【问题描述】:

我已经编写了在网页中搜索一些随机文本的代码块。该网页有多个标签,我正在使用 selenium 进行导航。这是我要查找的文本未在特定页面中修复的问题。文本可以位于网页中的任何选项卡中。如果未找到文本,则会引发异常。如果引发异常,则应转到下一个选项卡进行搜索。我在处理异常时遇到了困难。

下面是我正在尝试的代码。

import requests
from bs4 import BeautifulSoup
import re
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://www.yxx.com/71463001")
a = driver.page_source
soup = BeautifulSoup(a, "html.parser")

try:
    head = soup.find_all("div", {"style":"overflow:hidden;max-height:25px"})
    head_str = str(head)
    z = re.search('B00.{7}', head_str).group(0)
    print z
    print 'header'
except AttributeError:
    g_info = soup.find_all("div", {"id":"details_readonly"})
    g_info1=str(g_info)
    x = re.search('B00.{7}', g_info1).group(0)
    print x
    print 'description'
except AttributeError:
    corre = driver.find_element_by_id("tab_correspondence")
    corre.click()
    corr_g_info = soup.find_all("table", {"id" : "correspondence_view"})
    corr_g_info1=str(corr_g_info)
    print corr_g_info
    y = re.search('B00.{7}', corr_g_info1).group(0)
    print y
    print 'correspondance'

当我运行这段代码时,我得到一个

error Traceback (most recent call last):
  File "C:\Python27\BS.py", line 21, in <module>
    x = re.search('B00.{7}', g_info1).group(0)
AttributeError: 'NoneType' object has no attribute 'group'

【问题讨论】:

    标签: python-2.7 selenium-webdriver exception-handling beautifulsoup


    【解决方案1】:

    您收到该错误是因为您在一个不包含任何内容的 re.search 对象上调用 group。当我运行您的代码时,它会失败,因为您尝试连接的页面当前未启动。

    至于为什么你的except 没有注意到它:你错误地将两个excepts 写成了一个trytry 只会在第一个except 之前 捕获任何AttributeErrors。

    通过将第 19 行更改为 x = re.search('B00.{7}', g_info1),代码运行并返回 Nonedescription - 再次,因为页面当前未启动。

    或者,为了实现我认为你想要的,嵌套 try/except 是一种选择:

    try:
        head = soup.find_all("div", {"style":"overflow:hidden;max-height:25px"})
        head_str = str(head)
        z = re.search('B00.{7}', head_str).group(0)
        print z
        print 'header'
    except AttributeError:
        try:
            g_info = soup.find_all("div", {"id":"details_readonly"})
            g_info1=str(g_info)
            x = re.search('B00.{7}', g_info1)
            print x
            print 'description'
        except AttributeError:
            corre = driver.find_element_by_id("tab_correspondence")
            corre.click()
            corr_g_info = soup.find_all("table", {"id" : "correspondence_view"})
            corr_g_info1=str(corr_g_info)
            print corr_g_info
            y = re.search('B00.{7}', corr_g_info1).group(0)
            print y
            print 'correspondance'
    

    当然,此代码当前会抛出 NameError,因为在站点上没有定义 corr_g_info 变量的信息。

    【讨论】:

    • 谢谢你的作品。添加嵌套的 try catch 有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多