0
点赞
收藏
分享

微信扫一扫

Python网络爬虫《四》


1、Beautiful Soup指令安装(二选一):

  • pip install beautifulsoup4
  • easy_install beautifulsoup4

#/usr/bin/env.python
#_*_utf-8_*_
from bs4 import BeautifulSoup
import requests
if __name__=="__main__":
    url="http://www.baidu.com"
    r= requests.get(url)
    r.encoding = r.apparent_encoding
    demo =  r.text
    soup = BeautifulSoup(demo)
    print soup.prettify("gbk")


查看HTML:右键审查元素




2、BeautifulSoup库基本元素:




BeautifulSoup库是解析、遍历、维护“标签树”的功能库。




                     

Python网络爬虫《四》_HTML


                     

Python网络爬虫《四》_HTML_02


2、基于bs4库的HTML内容遍历:


                     

Python网络爬虫《四》_HTML_03



#/usr/bin/env.python
#coding:utf-8

from bs4 import BeautifulSoup
import requests
if __name__=="__main__":
    url="http://www.baidu.com"
    r= requests.get(url)
    r.encoding = r.apparent_encoding
    demo =  r.text
    soup = BeautifulSoup(demo,"html.parser")
    print "soup.head:",soup.head,"/n"
    print "------------------------------------"
    print "soup.head.contents:",soup.head.contents
    print "------------------------------------"
    print "soup.body.contents:",soup.body.contents
    print "------------------------------------"
    print "遍历子节点"
    for child in soup.body.children:
        print child
    print "------------------------------------"
    print "遍历子孙节点"
    for child in soup.title.descendants:
        print child
    print "------------------------------------"
    print "遍历父亲节点"
    for parent in soup.title.parents: #迭代类型
        if parent is None:
            print parent
        else:
            print parent.name
    print "平行遍历"
    print soup.body.next_sibling,soup.body.previous_sibling
    for sibling in soup.body.next_siblings: #previous_siblings迭代类型
        print sibling
    print soup.prettify("gbk")  #格式化输出





3、基于bs4库的HTML格式化输出





print soup.prettify("gbk") #格式化输出·





4、信息标记的三种方式




XML :扩展标记语言 

JSON:键值对

YAML:

缩进表达所述关系                    



 -  表并列关系



|  表示整块数据(#注释)

Python网络爬虫《四》_格式化输出_04

Python网络爬虫《四》_HTML_05

Python网络爬虫《四》_python_06


    对比:


  • XML:Internet上的信息交互和传递;
  • JSON:移动应用云端和节点的信息通信,无法注释;
  • YAML:各类系统的配置文件,有注释易读;




5、信息提取方法




方法一:形式解析


解析信息的标记形式-->提取关键信息

需要 标记解析器

优点:详细解析准确;

缺点:提取过程繁琐,速度慢;


方法二:搜索方法



对信息的文本 查找函数即可。

优点:过程简介,速度快;

缺点:提取结果准确性和内容相关;


结合两种方法:




#/usr/bin/env.python
# coding:utf-8
from bs4 import BeautifulSoup
import requests
if __name__=="__main__":
    url="http://www.baidu.com"
    r= requests.get(url)
    r.encoding = r.apparent_encoding
    demo =  r.text
    soup = BeautifulSoup(demo,"html.parser")
    #print soup.prettify("gbk")
    for link in soup.find_all('a'):
        print link.get('href')

注:




find_all ( self , name= None , attrs={}, recursive= True , text= None , limit= None , **kwargs):




注:


name:可以传字符串、正则表达式、列表、True、方法;


recursive :是否查找子节点所有,


text:文本内容;


limit:限制搜索结果的数量




其它:




Python网络爬虫《四》_格式化输出_07





















举报

相关推荐

0 条评论