Python网络爬虫与信息提取02

如何解析HTML页面信息标记和提取方法

BEAUTIFUL SOUP

实战项目

实例一 中国大学排名爬虫Projects

BEAUTIFUL SOUP可以爬取和解析

pip install beautifulsoup4

 

import requests

r=requests.get("http://python123.io/ws/demo.html")

r.text

demo=r.text
from bs4 import BeautifulSoup

soup=BeautifulSoup(demo,"html.parser")

print(soup.prettify())
 

 

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

BeautifulSoup类和标签树和HTML文档等价

BeautifulSoup类使标签树成一个变量,进行处理

 

from bs4 import BeautifulSoup

soup=BeautifulSoup(demo,"html.parser")
soup.title
tag=soup.a
tag.attrs soup.a.name soup.a.parent.name

 

 

 

 基于bs4遍历来获取HTML的内容

标签树的下行遍历

soup=BeautifulSoup(demo, "html.parser")
soup.head
soup.head.contents
soup.boddy.contents
len(soup.body.contents)
for child in soup.body.children:
    print(child)

 

标签树的上行遍历

标签树的平行遍历(所有的平行遍历在同一个父节点下的各节点间)

 

posted on 2017-09-11 17:06  AlexGui  阅读(172)  评论(0编辑  收藏  举报

导航