bs4基本案列使用
bs4基本解析:https://blog.csdn.net/A496608119/article/details/115689361?spm=1001.2014.3001.5501
直接上案列:爬取北京新发地的菜价格
代码如下:
# 1. 拿到页面源代码
# 2. 使用bs4进行解析,拿到数据
import requests
from bs4 import BeautifulSoup
import csv
# 1. 拿到页面源代码
url = "http://www.xinfadi.com.cn/marketanalysis/0/list/1.shtml"
resp = requests.get(url)
f = open("菜价.csv", mode="w", encoding='utf-8')
csvwriter = csv.writer(f)
# print(resp.text) 检查下网页能不能正常获取
# 2. 解析数据
# 2.1 把页面源代码交给BeautifulSoup进行处理,生成bs对象
page = BeautifulSoup(resp.text, "html.parser") # "html.parser" 指定html解析器,否则有警告
# 2.2 从bs对象中查找数据
# find(标签, 属性=值)找一个
# find_all 找一堆
# page.find("table", class="hq_table") # class是pyth的关键字,所以会报错,但是可以加下划线区别
# table = page.find("table", class_="hq_table")
table = page.find("table", attrs={"class": "hq_table"}) # 这样也能避免错误,和上面_效果一样
# 拿到所有数据进行切片,tr代表行,td代表列
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 表示拿到被标签标记的内容
gui = tds[4].text # .text 表示拿到被标签标记的内容
kind = tds[5].text # .text 表示拿到被标签标记的内容
date = tds[6].text # .text 表示拿到被标签标记的内容
print(name, low, avg, high, gui, kind, date)
csvwriter.writerows([name, low, avg, high, gui, kind, date])
f.close()
print("over!")
bs4进阶案列——抓取优美图库
抓取到了优美图库里的一些图片下载地址:
1.拿到主页面的源代码, 然后提取到子页面的链接地址,href
2.通过href进入子页面拿到子页面的内容, 从子页面中找到图片的下载地址 img -> src
3.下载图片
代码如下:
# 1.拿到主页面的源代码, 然后提取到子页面的链接地址,href
# 2.通过href进入子页面拿到子页面的内容, 从子页面中找到图片的下载地址 img -> src
# 3.下载图片
import requests
from bs4 import BeautifulSoup
import time
url = "https://www.umei.cc/bizhitupian/weimeibizhi/"
resp = requests.get(url)
resp.encoding = 'utf-8' # 处理乱码
# 把源代码交给bs
main_page = BeautifulSoup(resp.text, "html.parser")
alist = main_page.find("div", class_="TypeList").find_all("a")
for a in alist:
href = a.get('href')
# print(a.get('href')) # 直接通过get就可以拿到属性的值
# 拿到子页面的源代码
child_page_resp = requests.get(href)
child_page_resp.encoding = 'utf-8'
child_page_text = child_page_resp.text
# 从子页面中拿到图片的下载路径
child_page = BeautifulSoup(child_page_text, "html.parser")
img = child_page.find("p", align="center").find("img")
print(img.get("src"))
# src = img.get("src")
# 下载图片
# img_resp = requests.get(src)
# img_resp.content # 这里拿到的是字节
# img_name =src.split("/")[-1] # 拿到url中的最后一个/以后的内容
# with open(img_name, mode="wb") as f:
# f.write(img_resp.content) # 图片内容写入文件
# print("over!", img_name)
# time.sleep(1)
print("all_over")