前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >4.python读写csv文件

4.python读写csv文件

作者头像
zhang_derek
发布2019-08-14 14:18:21
4640
发布2019-08-14 14:18:21
举报
文章被收录于专栏:有趣的django有趣的django
代码语言:javascript
复制
import requests
import json
import csv
from bs4 import BeautifulSoup

books = []

def book_name(url):
    res = requests.get(url)
    html = res.text
    soup = BeautifulSoup(html, 'html.parser')
    items = soup.find(class_="grid-16-8 clearfix").find(class_="indent").find_all('table')

    for i in items:
        book = []
        title = i.find(class_="pl2").find('a')
        book.append('《' + title.text.replace(' ', '').replace('\n', '') + '》')

        star = i.find(class_="star clearfix").find(class_="rating_nums")
        book.append(star.text + '分')

        try:
            brief = i.find(class_="quote").find(class_="inq")
        except AttributeError:
            book.append('”暂无简介“')
        else:
            book.append(brief.text)

        link = i.find(class_="pl2").find('a')['href']
        book.append(link)

        global books
        books.append(book)

        print(book)

    try:
        next = soup.find(class_="paginator").find(class_="next").find('a')['href']
    # 翻到最后一页
    except TypeError:
        return 0
    else:
        return next


next = 'https://book.douban.com/top250?start=0&filter='
count = 0

while next != 0:
    count += 1
    next = book_name(next)
    print('-----------以上是第' + str(count) + '页的内容-----------')

csv_file = open('D:/top250_books.csv', 'w', newline='', encoding='utf-8')
w = csv.writer(csv_file)
w.writerow(['书名', '评分', '简介', '链接'])
for b in books:
    w.writerow(b)

结果

2.

代码语言:javascript
复制
'''
1.爬取豆瓣评分排行前250本书,保存为top250.csv
2.读取top250.csv文件,把评分为9.0以上的书籍保存到另外一个csv文件中
'''

import csv

#打开的时候必须用encoding='utf-8',否则报错
with open('top250.csv', encoding='utf-8') as rf:
    reader = csv.reader(rf)
    #读取头部
    headers = next(reader)
    with open('books_out.csv', 'w', encoding='utf-8') as wf:
        writer = csv.writer(wf)
        #把头部信息写进去
        writer.writerow(headers)

        for book in reader:
            #获取评分
            score = book[1]
            #把评分大于9.0的过滤出来
            if score and float(score) >= 9.0:
                writer.writerow(book)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 2.
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档