遍历html标签

时间:2020-05-01 13:42:12

标签: python web-scraping beautifulsoup html-parsing

我正在尝试使用html解析器和beautifulsoup抓取网页。我正在尝试从某些

标记获取文本。但是由于其中一些根本没有文本,所以对于那些为空的属性,我会遇到属性错误。我正在尝试以下代码:

content = elements.find("p",{"class":"Text"}).text #Where elements is a bs4 tag inside a for loop 

经过几次迭代后,出现以下错误:

AttributeError: 'NoneType' object has no attribute 'text'

也许我将不得不尝试以下操作:

while True:
    content = elements.find("p",{"class":"Text"}).text
    if type(content)==None:
        content = 'None'

但是上面的代码有问题

1 个答案:

答案 0 :(得分:0)

在访问元素的text属性之前,您必须检查该元素是否不是None

while True:
    elem = elements.find("p",{"class":"Text"})
    if elem is not None:
        content = elem.text
    else:
        content = 'None'  # Any static value you want to give
相关问题