BeautifulSoup是python解析html非常好用的第三方库;根据响应结果解析页面,提取数据
1.安装
pip install beautifulsoup4
2.导入
form bs4 import BeautifulSoup
3.用法
BeautifulSoup(网页源码,解析器)
4.解析器
| 序号 | 解析库 | 使用方法 | 优势 | 劣势 |
|---|---|---|---|---|
| 1 | Python标准库 | BeautifulSoup(html,’html.parser’) | Python内置标准库;执行速度快 | 容错能力较差 |
| 2 | lxml HTML解析库 | BeautifulSoup(html,’lxml’) | 速度快;容错能力强 | 需安装C语言库 |
| 3 | lxml XML解析库 | BeautifulSoup(html,[‘lxml’,’xml’]) | 速度快;容错能力强;支持XML格式 | 需安装C语言库 |
| 4 | htm5lib解析库 | BeautifulSoup(html,’htm5llib’) | 以浏览器方式解析,最好的容错性 | 速度慢 |
-------------------------------------
网页分为静态页面和动态页面静态页面:内容是写死的,除非人为修改,否则内容一成不变
动态页面:内容不是写死的,使用某种特殊的技术(javascript)使页面中的数据显示在页面中requests得到的结 果是静态页面的内容
-------------------------------------
网页右键检查—Elements:此处代码可能是伪代码,显示的是完全加载之后的代码
request和查看网页源代码是真实的
-------------------------------------
代码:爬虫demo
import requests
from bs4 import BeautifulSoup
# bs4模块能够从html或者xml中提取数据
# URL='https://101.qq.com/#/hero'
for page in range(1,11):
print(f'第{page}页信息')
URL = f'https://www.chinanews.com.cn/scroll-news/news{page}.html'.format(page)
# headers={}--->headers是一个字典:{key:value}
# headers是给爬虫提供伪装的
# User-Agent --> 将爬虫伪装成浏览器
# User-Agent怎么找:网页右键检查-Network-All-页面刷新-点击第一个文件-Headers-User-Agent
Headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
resp=requests.get(url=URL,headers=Headers)
if resp.status_code==200:
# 解决乱码
resp.encoding='utf-8'
# resp.encoding='gbk'
# 打印网页源码(字符串)
# print(resp.text)
soup= BeautifulSoup(resp.text,'html.parser')
# print(soup,type(soup))
li_list=soup.select('body>div.w1280.mt20>div.content-left>'
'div.content_list>ul>li')
# print(li_list)
for i in li_list:
# print(i)
if i.select_one('li>div.dd_lm>a')!=None:
news_type=i.select_one('li>div.dd_lm>a').text
if i.select_one('li>div.dd_bt>a')!=None:
news_href='https://www.chinanews.com.cn'+i.select_one('li>div.dd_bt>a').attrs['href']
news_title=i.select_one('li>div.dd_bt>a').text
news_time=i.select_one('li>div.dd_time').text
print(news_type,news_title,news_href,news_time)



