python爬虫之BeatifulSoup

#安装
#pip install bs4

#1.拿到页面源代码
#2.使用bs4进行解析,拿到数据
import requests
from bs4 import BeautifulSoup
import csv
import re

url = "http://www.xinfadi.com.cn/getPriceData.html"
resp = requests.get(url)
resp.close()
# print(resp.text)

f = open("菜价.csv", mode="w",encoding='utf-8')
csvwriter = csv.writer(f)

#解析数据
#1.把页面源代码交给BeautifulSoup进行处理,生成bs对象
# page = BeautifulSoup(resp.text, "html.parser")#指定html解析器
obj1 = re.compile(r',"prodName":"(?P<name>.*?)",.*?"prodCat":"(?P<type>.*?)",.*?"lowPrice":"(?P<lowPrice>.*?)",.*?'
                  r'"highPrice":"(?P<highPrice>.*?)",.*?"avgPrice":"(?P<avgPrice>.*?)",', re.S)
result1 = obj1.finditer(resp.text)
for it in result1:

    dic = it.groupdict()
    csvwriter.writerow(dic.values())
f.close()
print("over!")
#2.从bs对象种查找数据
#find(标签,属性=值)
#find_all(标签,属性=值)
# table = page.find("table","class_="hq_table")  #加_因为class是python的关键字
# table = page.find("table",attrrs={"class": hq_table"})  #加_因为class是python的关键字
# print(page.text)
#拿到所有数据行
# trs = table.find_all("tr")[1:]
# for tr in trs:  #每一行
#     tds = tr.find_all("td")     #拿到每行中的所有td
#     name = tds[0].text      #.text表示拿到被标签所标记的内容
#     type = tds[1].text
#     max = tds[2].text
#     min = tds[3].text
#     avg = tds[4].text
#     csvwriter.writerow([name,type,max,min,avg])
#
# f.close()
# print("over!")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值