一、BeautifulSoup爬虫介绍
1.1、简要介绍:是一个用于解析HTML和XML文档的Python库。它能够从网页中提取数据,并且可以处理不规范的标记,主要的方法有find_all()find_all()
import csv
import requests
from bs4 import BeautifulSoup
# 步骤1:拿到页面源数据 步骤2:使用bs4进行解析,拿到数据
# 改url无效,本代码只是为了练习
url = "http://www.xinfadi.com.cn/marketanalysis/0/list/1.shtml"
resp = requests.get(url)
print(resp.text)
file = open("priceInfo.csv", mode="w", encoding="gb2312")
write = csv.writer(file)
# 解析数据
# 1.将页面源代码交给BeautifulSoup进行处理,生成bs对象
page = BeautifulSoup(resp.text, "html.parser") # 指定html解析器
# 2,从bs对象中查找数据
# find(标签,属性=值)
# find_all(标签,属性=值)
# table = page.find("table",class_="qt_table") # class 是python中的关键字,因此用class_来替代class
table = page.find("table",attrs={"class":"qt_table"}) # 同等上一行,只是避免使用了class关键字
trs = table.find_all("tr")[1:] # 找到表格中的除去表头的全部行
for tr in trs:
tds = tr.find_all("td") # 拿到行中所有td
name = tds[0].text # .text是拿到被标签标记的内容
low = tds[1].text # .text是拿到被标签标记的内容
avg = tds[2].text # .text是拿到被标签标记的内容
high = tds[3].text # .text是拿到被标签标记的内容
date = tds[4].text # .text是拿到被标签标记的内容
write.writerow([name, low, avg, high, date])
# print(name, low, avg, high, date
file.close()
print("write over!")
二、BeautifulSoup爬虫案例
2.1、获取优美图库的图片信息(首页-下载完成的图片信息)
"""
练习爬取图片资源
步骤一:拿到主页面的源代码,然后提取到子页面的链接地址href
步骤二:通过href拿到子页面的地址,从子页面中找到图片的下载地址 img->src
步骤三:通过src链接下载图片
"""
import requests
from bs4 import BeautifulSoup
import time,os
# 定义下载图片后保存的位置
folder_path = 'D:\\ProjectCode\\Spider\\StudySpider03\\imgs'
# 检查文件夹是否存在
if not os.path.exists(folder_path):
# 如果文件夹不存在,则创建文件夹
os.makedirs(folder_path)
print(f"文件夹 {folder_path} 已创建。")
else:
print(f"文件夹 {folder_path} 已存在。")
url = "https://www.umeituku.com/p/gaoqing/"
resp = requests.get(url)
resp.encoding = "UTF-8"
# print(resp.text)
main_page = BeautifulSoup(resp.text, "html.parser")
a_list = main_page.find("div", class_="TypeList").find_all("a")
for a in a_list:
# print(a.get("href")) # 通过get可以获取到标签里面的属性值
# 获取到子页面的链接地址
href = a.get("href")
# 根据子页面的链接地址发送请求,获取子页面的源代码
child_resp = requests.get(href)
child_resp.encoding = "UTF-8"
child_page = BeautifulSoup(child_resp.text, "html.parser")
child_a_list = child_page.find("div", class_="ImageBody").find("a").find("img")
# 得到子页面图片的下载地址
# print(child_a_list.get("src"))
pic_src = child_a_list.get("src")
print(pic_src)
# 下载图片
img_resp = requests.get(pic_src)
img_name = pic_src.split("/")[-1]
# 定义图片的下载路径
file_path = os.path.join(folder_path, img_name)
# 在保存图片时,勿使用文本模式("w"),这通常用于文本文件。对于图片,应该使用二进制模式("wb")来保存
# 此外在保存图片时,你不需要指定编码,因为图片是二进制数据
with open(file_path, mode="wb") as f:
f.write(img_resp.content) # img_resp.content是获取字节,将图片字节写入到文件中
print(img_name, "download over!")
time.sleep(1)
print("all download over!")