编程语言
首页 > 编程语言> > Python爬虫--BeautifulSoup解析器

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)

标签:解析器,lxml,HTML,Python,BeautifulSoup,--,html,url
来源: https://blog.csdn.net/qq_40523659/article/details/122644881