首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >写入csv时出错,不允许我写入Python3和csvwriter

写入csv时出错,不允许我写入Python3和csvwriter
EN

Stack Overflow用户
提问于 2018-06-14 03:37:10
回答 1查看 26关注 0票数 0

这段代码有问题:

代码语言:javascript
复制
    i = range(0, 51)

    page_number = 1
    with open('hltb data/HLTB.csv','w') as f: 
        thewriter = csv.writer(f)
        thewriter.writerow(['Game Name:', 'Game Length:', 'Game Developer:', "Game Publisher:", 'Game Genre:', 'Game Console:', 'URL:']) 
 for element in i:
        url = 'https://howlongtobeat.com/game.php?id=' + format(page_number)

        response = get(url)
        html_soup = BeautifulSoup(response.text, 'html.parser')

        page_number += 1

        try:
            game_name = html_soup.select('div.profile_header')[0].text
        except:
            game_name = "Game Name not found"

        try:     
            game_length = html_soup.select('div.game_times li div')[-1].string
        except:
            game_length = "Game length not found"

        try:
            game_developer = html_soup.find_all('strong', string='\nDeveloper:\n')[0].next_sibling
        except:
            game_developer = "Game developer not found"

        try:
            game_publisher = html_soup.find_all('strong', string='\nPublisher:\n')[0].next_sibling
        except:
            game_publisher = "Game Publisher not found"

        try:
            game_console = html_soup.find_all('strong', string='\nPlayable On:\n')[0].next_sibling
        except:
            game_console = "Game Playable on not found"

        try:
            game_genres = html_soup.find_all('strong', string='\nGenres:\n')[0].next_sibling
        except:
            game_genres = "Game Genres found"

        print(url)
        print(game_name)
        print(game_length)
        print(game_developer)
        print(game_publisher)
        print(game_genres)
        print(game_console)

        row = [game_name, game_length, game_developer, game_publisher, game_genres, game_console, url]
        thewriter.writerow(row)

当我运行代码时,我得到了这个错误:

行回溯(最近一次调用) () 46 47

= game_name,game_length,game_developer,game_publisher,game_genres,game_console,url -> 48 thewriter.writerow(行)

ValueError:已关闭文件的I/O操作。

我以前让它工作过。

如何进行数据抓取并将信息转换为电子表格,以便我可以操作数据?

EN

回答 1

Stack Overflow用户

发布于 2018-06-14 03:50:51

看起来像是在打开的文件上的with open()外部执行for循环。移动for循环,使其包含在with open()

代码语言:javascript
复制
[...]
with open('hltb data/HLTB.csv','w') as f: 
    thewriter = csv.writer(f)
    thewriter.writerow(['Game Name:', 'Game Length:', 'Game Developer:', "Game Publisher:", 'Game Genre:', 'Game Console:', 'URL:']) 
    for element in i:
        url = 'https://howlongtobeat.com/game.php?id=' + format(page_number)
        [...]

编辑:我指的是with open(),不是while。修复了我的帖子,我正在煮咖啡。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50844975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档