Python bs4的基本使用,爬北京市场菜价
# coding:utf-8
from bs4 import BeautifulSoup
import requests
import csv
#1.拿到页面源代码
#2.使用bs4进行解析,拿到数据
url = 'http://www.xinfadi.com.cn/'
resp=requests.get(url)
resp.encoding='utf-8'
f = (open("xfd_data.csv", mode="w"))
csvwriter = csv.writer(f)
# print(resp.text)
#解析数据
#1。把页面源代码交给BeautifulSoup,进行处理,生成对象
page = BeautifulSoup(resp.text,"html.parser")#指定html解析器
#2.从bs4对象中查找数据
#find(标签,属性=值)
#findall(标签,属性=值)
# conLi=page.find("li",class_="conLi") #class是python关键字
conLi=page.findAll("li",attrs={ #和上一行一个意思
"class":"conLi"
})#class是python关键字
for con in conLi:
cons=con.find_all("em")
name = cons[0].text
low = cons[1].text
avg = cons[2].text
max = cons[3].text
save = cons[4].text
kg = cons[5].text
time = cons[6].text
print(name,low,avg,max,save,kg,time)
csvwriter.writerow([name,low,avg,max,save,kg,time])
f.close()
print("over")