beautifulsoup3.2.1使用时遇到的一些小问题,,参考了文档 然后根据他的
beautifulsoup3.2.1使用时遇到的一些小问题,,参考了文档 然后根据他的
参考了文档 然后根据他的例子做了
其中他文档中的例子是
from BeautifulSoup import BeautifulSoup doc = ['<html><head><title>Page title</title></head>', '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.', '<p id="secondpara" align="blah">This is paragraph <b>two</b>.', '</html>']soup = BeautifulSoup(''.join(doc))print soup.head.nextSibling.name
然后输出了body
但是如果我改成下面这个样子
from BeautifulSoup import BeautifulSouphtml = ''' <html> <head> <title> Page title </title> </head> <body> <p id="firstpara" align="center"> This is paragraph <b> one </b> . </p> <p id="secondpara" align="blah"> This is paragraph <b> two </b> . </p> </body> </html> '''soup = BeautifulSoup(html)print soup.head.nextSibling.name
结果会出错,出错信息是
File "/Library/Python/2.7/site-packages/BeautifulSoup.py", line 473, in __getattr__ raise AttributeError, "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)AttributeError: 'NavigableString' object has no attribute 'name'
但是如果把上面代码中最后一句使用nextSibling的代码改成下面的形式
print soup.head.nextSibling.nextSibling.name
就又可以正确输出结果了,输出了body
但是一般我们爬取网页返回的都是第二种情况,然后我看了一些开源的抓取其他网页的webservice开源代码,其中也是连续用了两次nextSibling才获取下一个同级元素,想请问下各位大大为什么第二种情况就一定要连续用两次nextSibling才能获得下一个同级dom元素呢,nextSibling不是本意就是下一个同级元素,为什么此处需要用两次才能获取下一个,只用一次就会出现上面那个错误。
soup.head.nextSibling 应该是获取到了 head 标签后边的文本节点吧?
经测试,beautifulsoup4 只需要一个 .nextSibling 就取到了 <body> 元素。
编橙之家文章,
相关内容
- 谁能分享Python OpenStack高质量的部署资料,pythonopenstac
- 参照教程的Flask操作显示AttributeError是什么问题,,Flas
- 只有python2.6o可以在sx版本mod_wsgi中使用吗?,python2.6omo
- python语言中为什么说getter和setter用起来很傻,getterset
- 有比python comet框架功能更好的开源框架码,pythoncomet,想
- linux下多个python版本切换如何设置,linuxpython,比如自带
- django model实现,如何实现外键对多种模型,djangomodel,就是
- Python闪退问题,py2exe打包执行闪退了怎么调整,pythonpy
- python不同版本list内中文输出问题,python不同版本,foo
- python函数应用请大神帮我看代码问题,python大神,问这个
评论关闭