使用python将口袋妖怪从GitHub保存为CSV

2024-10-03 06:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python世界的新手,想知道如何将数据从github刮到CSV文件中,例如。 https://gist.github.com/simsketch/1a029a8d7fca1e4c142cbfd043a68f19#file-pokemon-csv

我正在尝试这段代码,但是它不是很成功。当然,应该有一个更简单的方法

提前谢谢你

from bs4 import BeautifulSoup
import requests
import csv

url = 'https://gist.github.com/simsketch/1a029a8d7fca1e4c142cbfd043a68f19'

r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')

pokemon_table = soup.find('table', class_= 'highlight tab-size js-file-line-container')


for pokemon in pokemon_table.find_all('tr'):
        name = [pokemon.find('td', class_= 'blob-code blob-code-inner js-file-line').text]


with open('output.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(name)


Tags: csvhttpsimportgithubcomurltablefind
1条回答
网友
1楼 · 发布于 2024-10-03 06:21:31

如果您不介意使用CSV文件的“原始版本”,则以下代码可以工作:

import requests

response = requests.get("https://gist.githubusercontent.com/simsketch/1a029a8d7fca1e4c142cbfd043a68f19/raw/bd584ee6c307cc9fab5ba38916e98a85de9c2ba7/pokemon.csv")

with open("output.csv", "w") as file:
    file.write(response.text)

您正在使用的URL不会链接到CSV的原始版本,但以下URL会链接到CSV:

https://gist.githubusercontent.com/simsketch/1a029a8d7fca1e4c142cbfd043a68f19/raw/bd584ee6c307cc9fab5ba38916e98a85de9c2ba7/pokemon.csv

编辑1:为了澄清这一点,您可以按您提供的链接中显示的CSV文件右上角的“Raw”按钮访问该CSV文件的原始版本

编辑2:此外,以下URL看起来也可以使用,而且它更短,更易于基于原始URL进行“构建”: https://gist.githubusercontent.com/simsketch/1a029a8d7fca1e4c142cbfd043a68f19/raw/pokemon.csv

相关问题 更多 >