示例代码,仅供参考
import requests
from bs4 import BeautifulSoup
import csv
# 针对html页面数据,而不是服务器端返回的json数据
url="http://www.xinfadi.com.cn/getPriceData.html"#url不适用于该情况
resp=requests.get(url)
f=open("菜价.csv",mode="w")
csvwriter=csv.writer(f)
# print(resp.text)
# 解析数据
page=BeautifulSoup(resp.text,"html.parser")#指定html解析器
# 从bs4对象中找数据
# find(标签,属性=值)
# find_all(标签,属性=值)
# table=page.find("table",class_="hq_table")
table=page.find("table",attrs={"class":"hq_table"})
# print(table)
#拿到所有数据行
trs=table.find_all("tr")[1:]
for tr in trs:
tds=tr.find_all("td")
name = tds[0].text
low = tds[1].text
high = tds[2].text
csvwriter.writerow([name,low,high])
f.close()
print("over")