【发布时间】:2018-07-21 11:34:33
【问题描述】:
这是我第一次使用 Python 2.7,我很喜欢。但是,我试图弄清楚如何将从 URL 中提取的数据放入 CSV 文件中。我找到了this tutorial,但是当我运行我的脚本时:
# import libraries
import csv
import urllib2
from bs4 import BeautifulSoup
# specify the url
quote_page = 'http://www.bkfrem.dk/default.asp?id=19'
# query the website and return the html to the variable ‘page’
page = urllib2.urlopen(quote_page)
# parse the html using beautiful soup and store in variable soup
soup = BeautifulSoup(page, 'html.parser')
# create CSV file
csvfile = csv.writer(open('firsteam.csv', 'w'))
csvfile.writerow(["Name", "Position"])
# take out the <div> of name and get its value
items = soup.find_all('div', attrs={'class': 'visTruppenContainer'})
for i in range(len(items)):
playerInfo = items[i].getText(separator=u' ')
imageURL = items[1].find('img')['src']
csvfile.writerow([playerInfo, imageURL])
print (playerInfo)
print (imageURL)
我收到此错误:
Traceback (most recent call last): File "C:/Users/User/Desktop/script2.py", line 26, in <module> csvfile.writerow([playerInfo, imageURL]) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe5' in position 27: ordinal not in range(128)
我做错了什么?在写入 CSV 文件之前是否必须转换数据?
【问题讨论】:
-
encode('utf-8')? -
我应该编码什么?输出?
-
你能用python 3代替吗?
-
在
csvfile.writerow([playerInfo, imageURL])中是的(我无法尝试,因为当我将它转换为 Python 3 时它可以工作)所以我不能告诉你确切的位置,但它肯定在这两个之一中 -
是的,现在我不再收到错误了,但是 CSV 文件是空的 :(
标签: python python-2.7 csv beautifulsoup