访问BeautifulSoup中的属性时出现问题

Nul*_*ion 6 python attributes beautifulsoup

我在使用Python(2.7)时遇到了问题.代码基本上包括:

str = '<el at="some">ABC</el><el>DEF</el>'
z = BeautifulStoneSoup(str)

for x in z.findAll('el'):
    # if 'at' in x:
    # if hasattr(x, 'at'):
        print x['at']   
    else:
        print 'nothing'
Run Code Online (Sandbox Code Playgroud)

我期望第一个if语句正常工作(即:如果at不存在,打印"nothing"),但它总是不打印(即:总是False).if另一方面,第二个是总是True,这将导致代码KeyError在尝试at从第二个<el>元素访问时引发,当然这不存在.

Eli*_*sky 7

in操作是序列和映射类型,是什么让你觉得通过返回的对象BeautifulSoup应该正确地实现它?根据BeautifulSoup文档,您应该使用[]语法访问属性.

Re hasattr,我认为你混淆了HTML/XML属性和Python对象属性.hasattr适用于后者,BeaitufulSoup AFAIK不反映它在自己的对象属性中解析的HTML/XML属性.

PS注意到Tag对象BeautifulSoup 确实实现了__contains__- 所以也许你正在尝试使用错误的对象?你能展示一个完整但最小的例子来证明这个问题吗?


运行这个:

from BeautifulSoup import BeautifulSoup

str = '<el at="some">ABC</el><el>DEF</el>'
z = BeautifulSoup(str)

for x in z.findAll('el'):
    print type(x)
    print x['at']
Run Code Online (Sandbox Code Playgroud)

我明白了:

<class 'BeautifulSoup.Tag'>
some
<class 'BeautifulSoup.Tag'>
Traceback (most recent call last):
  File "soup4.py", line 8, in <module>
    print x['at']
  File "C:\Python26\lib\site-packages\BeautifulSoup.py", line 601, in __getitem__
    return self._getAttrMap()[key]
KeyError: 'at'
Run Code Online (Sandbox Code Playgroud)

这是我的预期.第一个el有一个at属性,第二个没有 - 这会引发一个KeyError.


更新2:BeautifulSoup.Tag.__contains__里面看起来内容的标签,而不是它的属性.检查属性是否存在使用in.