python爬取信息并保存至csv


import csv
import requests
from bs4 import BeautifulSoup
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 in maindiv:
    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)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM