python三方库之BeautifuSoup

html文档解析的三方库beautifulsoup4

什么是beautifulsoup?

学习资源:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

1.安装

pip install beautifulsoup4

2.使用

至少要对html有一定的了解。

from bs4 import BeautifulSoup

举例:获取一个页面中的所有链接

def get_link(url="http://www.zhihu.com"):
    hrefs = []
    html = urllib2.urlopen(url=url).read()
    soup = BeautifulSoup(html, "html.parser")
    for link in soup.find_all('a'):
        href = link.get('href')
        if not href.startswith('http'):
            href = url + href
        hrefs.append(href)
    return hrefs



posted @ 2022-03-06 10:39  叶常落  阅读(32)  评论(0编辑  收藏  举报