摘要
如何用beautifulsoup4解析各种情况的网页
beautifulsoup4的使用
关于beautifulsoup4,官网已经讲的很详细了,我这里就把一些常用的解析方法做个总结,方便查阅。
装载html文档
使用beautifulsoup的第一步是把html文档装载到beautifulsoup中,使其形成一个beautifulsoup对象。

初始化BeautifulSoup类时,需要加入两个参数,第一个参数即是我们爬到html源码,第二个参数是html解析器,常用的有三个解析器,分别是”html.parser”,”lxml”,”html5lib”,官网推荐用lxml,因为效率高,当然需要pip install lxml一下。
当然这三种解析方式在某些情况解析得到的对象内容是不同的,比如对于标签不完整这一情况(p标签只有一半):

使用
在使用中,我尽量按照我使用的频率介绍,毕竟为了查阅~
按照标签名称、id、class等信息获取某个标签

按照标签名称、id、class等信息获取多个标签

按照标签的其他属性获取某个标签

找前头和后头的标签

找父标签
soup.find_parents("div")
soup.find_parent("div")
css选择器

注意几个可能出现的错误,可以用try捕获来防止爬虫进程
UnicodeEncodeError: ‘charmap' codec can't encode character u'\xfoo' in position bar (或其它类型的 UnicodeEncodeError
需要转码
AttributeError: ‘NoneType' object has no attribute ‘foo'
没这个属性
就介绍这么多,应该可以覆盖大部分网页结构了吧~!