importcsvimportrequestsfrom bs4 importBeautifulSoup
res=requests.get('http://books.toscrape.com/catalogue/category/books/travel_2/index.html')
html=res.text
soup=BeautifulSoup(html,'html.parser')
maindiv=soup.find_all(class_="col-xs-6 col-sm-4 col-md-3 col-lg-3")
f= open('hhh.csv','w',newline='',encoding='utf-8')
csv_writer=csv.writer(f)
csv_writer.writerow(['名称','价格','评价'])for item inmaindiv:
linedata1=[];
namediv=item.find('h3')
name=namediv.find('a')#print('名称:'+name['title'])
price=item.find(class_="price_color")#print('价格:'+price.text)
pf=item.find(class_="star-rating")#print('好评数:'+pf.attrs['class'][1])
linedata1.append(name['title'])
linedata1.append(price.text)
linedata1.append(pf.attrs['class'][1])
csv_writer.writerow(linedata1)