爬虫之用bs4解析数据

Beautiful Soup是将复杂HTML文档转换成一个复杂的树形结构
步骤:

  1. 拿到网页源代码

  2. 用bs4进行解析数据,拿到自己想要的数据 解析数据:
    <1>.把页面源代码交给BeautifulSoup进行处理,生产bs对象
    <2>.从bs对象中查找数据
    find(标签,属性=值) 查找第一个,返回一个BeautifulSoup的标签对象
    find_all(标签,属性=值) 查找全部,返回一个BeautifulSoup的标签对象

  3. 用csv保存数据

所需要的一点HTML的知识:

  1. 网页结构大概为:

    	<标签 属性=‘值’,属性=‘值’>
    		内容
    	</标签>
    
  2. 常见的标签:

    h1:一级标题
    h2:二级标题
    p:段落
    font:字体(被废弃,但能用)
    body:主体部分
    

本次实验以

http://www.maicainan.com/offer/show/id/4966.html

这个网站为实验对象,爬取里面的菜名所对应的菜价
在这里插入图片描述
先对其源代码进行分析
在这里插入图片描述
可以看到在标签table和属性class="f_s_14"内

那么我们上代码:

from bs4 import BeautifulSoup  #导入BeautifulSoup模块
import requests
import csv

url="http://www.maicainan.com/offer/show/id/4966.html"
header={
    
    
        "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"
}	#添加头部信息
with open("chaijia.csv",'w',newline='')as f:
    wirter=csv.writer(f)
    resp=requests.get(url)
    resp.encoding='utf-8'

    #解析数据
    #1.把页面源代码交给BeautifulSoup进行处理,生产bs对象
    html=BeautifulSoup(resp.text,"html.parser") #指定用html解析码
    #2.从bs对象中查找数据
    #find(标签,属性=值)  #查找第一个
    #find_all(标签,属性=值)  #查找全部
    table1=html.find_all("table",class_="f_s_14")[1] 
    table2=html.find_all("table",class_="f_s_14")[2] #class是python关键字,避免警告,则在关键字后添加_
    #拿到所有行的数据
    trs1=table1.find_all("tr")
    trs2=table2.find_all("tr")
    trs=trs1+trs2
    wirter.writerow(["菜名", "最低价", "最高价", "平均价"])
    for tr in trs:
        tds=tr.find_all("td")
        name=tds[0].text
        low=tds[1].text
        high=tds[2].text
        aver=tds[3].text
        wirter.writerow([name,low,high,aver])
print("over!")

运行结果:
在这里插入图片描述
在这里插入图片描述

Guess you like

Origin blog.csdn.net/qq_55977554/article/details/121340477
Recommended