import requests from bs4 import BeautifulSoup import csv url="http://u_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) be=BeautifulSoup(resp.text,"html.parser") table=be.find("table",class_="hq_table") # table=be.find("table",attrs={ "class":"hq_table"}) trs=table.find_all("tr")[1:] for tr in trs : tds=tr.find_all("td") name = tds[0].text q = tds[1].text w = tds[2].text e = tds[3].text r = tds[4].text t = tds[5].text y = tds[6].text csvwriter.writerow([name,q,w,e,r,t,y])
把csvwriter.writerow([name,q,w,e,r,t,y])放入for 循环内。