【问题标题】:How to read html tags using beautifulsoup如何使用 Beautifulsoup 读取 html 标签
【发布时间】:2014-03-01 00:09:34
【问题描述】:

我正在尝试使用 beautifulsoap 读取 html 标签并检查某些标签是否可用或缺失。

我正在使用 beautifulsoup 读取文件,然后在我的测试文件中使用它。

这是我尝试过但没有成功的方法:

class Testing(unittest.TestCase):
        @classmethod
        def setUp(name):

            name.html = None
            with open("index.html") as frd:
                name.html = frd.read()
                name.soup = BeautifulSoup(name.html)
            if not name.html:
                raise Exception('cant read')    

        def testing(self)
         assert self.soup.find('html') == 'html'
          #Raise : error

我无法在汤中使用 find() 函数找到 html 标记(尝试打印它以查看输出,但 dint 工作)。如果 html 文件中缺少 HTML 标签,如何引发异常?

【问题讨论】:

  • 您得到的确切错误是什么?我看到你没有 : 在定义之后!
  • 断言 self.soup.find('html') == 'html' AssertionError
  • 好的,你可以试试我刚刚发布的另一个答案吗?
  • 显示更多代码。具体来说,你在哪里初始化soup
  • 好的,试试这个答案,它工作正常!

标签: python beautifulsoup


【解决方案1】:

当你使用 find 时试试这个,它返回美化的字符串或无!所以,这个东西我可以推荐!

try:
    assert self.soup.find('html') != None
except AssertionError, e:
    raise Exception("HTML Tag is missing!")

【讨论】:

  • 对不起,不行!!我的文件中有 Html 标记,但它仍然引发 html 丢失的异常
  • 当它发现一些东西用 None 断言时:)
  • 这里如何使用 assertEqual ,我试过 self.assertEqual(self.soup.find('html'),"html") ,对吗?
  • 你不能这样做,因为你在比较 not None 和 "html",这是完全错误的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-30
  • 1970-01-01
  • 2021-12-05
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
相关资源
最近更新 更多