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