刚成立公司如何做网站网页设计首页尺寸
bs4进行数据解析
 -数据解析的原理:
 - 1.标签定位
 -2.提取标签、标签属性中存储的数据值
 - bs4数据解析的原理:
 - 1.实例化一个BeautifulSoup对象,并且将页面源码数据加载到该对象中
 -2.通过调用BeautifulSoup对象中相关的属性或者方法进行标签定位和数据提取
- 环境安装:
 - pip install bs4
 - pip install lxml
 - 如何实例化BeautifulSoup对象:
         - from bs4 import BeautifulSoup
                 -对象的案例化:
                         - 1.将本地的html文档中的数据加载到该对象中
                                 fp = open('./test.html','r', encoding='utf-8')
                                 soup = BeautifulSoup(fp, 'lxml')
                         - 2.将互联网上获取的页面源码加载到该对象中
                                 page_text = response. text
                                 soup = BeatifulSoup(page_text, 'lxml')
         - 提供的用于数据解析的方法和属性:
爬取三国演义文本数据
先使用通用爬虫爬取页面所有数据,再解析标题内容
import requests  # 导入requests库,用于发起网络请求
from bs4 import BeautifulSoup  # 导入BeautifulSoup库,用于解析网页内容# 设置要爬取的网站的URL和请求头信息
url = 'https://www.shicimingju.com/book/sanguoyanyi.html'  # 这是我们要爬取的网站地址
headers = {'User-Agent': 'Mozilla/5.0'}  # 这是告诉网站我们是用什么浏览器来访问的,这里用的是Mozilla/5.0,类似于Firefox# 使用requests发起网络请求,获取网页内容
page_text = requests.get(url=url, headers=headers).content  # 发起请求并获取返回的网页内容# 创建BeautifulSoup对象,用于解析网页内容
soup = BeautifulSoup(page_text, 'html.parser')  # 使用html.parser解析网页内容# 使用BeautifulSoup选择器找到包含章节标题和详情页URL的列表项
li_list = soup.select('.book-mulu > ul > li')  # 找到所有符合这个规则的列表项# 打开一个文件,准备写入解析到的内容
fp = open('./sanguo.txt', 'w', encoding='utf-8')  # 打开一个文件,准备写入解析到的内容# 遍历找到的列表项,解析每个章节的标题和详情页URL
for li in li_list:title = li.a.string  # 提取每个列表项中a标签内的文本内容,即章节标题detail_url = 'http://www.shicimingju.com' + li.a['href']  # 构建每个章节的详情页URL# 对每个详情页发起网络请求,获取详情页内容try:detail_page_text = requests.get(url=detail_url, headers=headers).content  # 发起请求并获取返回的详情页内容detail_soup = BeautifulSoup(detail_page_text, 'html.parser')  # 使用html.parser解析详情页内容div_tag = detail_soup.find('div', class_='chapter_content')  # 找到包含章节内容的div标签if div_tag:  # 如果找到章节内容div标签content = div_tag.text  # 提取章节内容文本fp.write(title + ':' + content + '\n')  # 将章节标题和内容写入文件,每行一个print(title, '爬取成功!!!')  # 打印章节标题,表示成功爬取else:print(title, '内容解析失败!!!')  # 打印章节标题,表示内容解析失败except requests.exceptions.RequestException as e:  # 处理可能出现的网络请求异常print(f'请求失败: {e}')  # 打印错误信息# 完成所有章节的解析和写入后,关闭文件
fp.close()  # 关闭文件
 
