Python爬虫--BeautifulSoup解析器

2022/1/23 11:04:18

本文主要是介绍Python爬虫--BeautifulSoup解析器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1.BeautifulSoup

是一个可以从HTML或XML文件中提取数据的Python库,使用前需安装:pip install bs4

BeautifulSoup支持Python标准库中的HTML解析器,还支持第三方解析器,默认使用HTML解析器。

解析器语法结构优点缺点
标准库BeautifulSoup(html,‘html.parser’)内置标准库,速度适中Python3.2版本前的文档容错能力差
lxml HTMLBeautifulSoup(html,‘lxml’)速度快,文档容错能力强安装C语言库
lxml XMLBeautifulSoup(html,‘xml’)速度快,唯一支持XML安装C语言库
html5libBeautifulSoup(html,‘html5lib’)容错能力最强,可生成HTML5运行慢,扩展差

2.爬取淘宝网上的超链接

import requests
from bs4 import BeautifulSoup
url = 'https://www.taobao.com/'
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'}
resp = requests.get(url,headers)
bs = BeautifulSoup(resp.text,'lxml')
a_list = bs.find_all('a') #查找所有的a标签
for a in a_list:
    #获取每个a标签的href
    url = a.get('href')
    if url == None:
        continue
    if url.startswith('http') or url.startswith('https'):
        print(url)


这篇关于Python爬虫--BeautifulSoup解析器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程