使用 python 的奇怪 csv 输出
weird csv output using python
我最近尝试抓取 http://quotes.toscrape.com/ 引号(仅在第一页)并将它们保存到 csv 文件中。我得到了一个很奇怪的结果。仅使用逗号作为分隔符。请参阅下面的屏幕截图和代码:
from bs4 import BeautifulSoup
from urllib.request import urlopen
import csv
csvfile = open('quotes.csv', 'w')
writer = csv.writer(csvfile)
writer.writerow(('text'))
def parse():
html = urlopen('http://quotes.toscrape.com/page/1/')
bs = BeautifulSoup(html, 'lxml')
quotes = bs.findAll('div', class_='quote')
for quote in quotes:
try:
text = quote.find('span', class_='text').getText(
).replace(',', '|').replace('"', '')
print(text)
writer.writerow((text))
except UnicodeEncodeError:
break
parse()
csvfile.close()
您已尝试使用带有元组的写入行,但是(奇怪的怪癖)您实际上并没有使用元组。
看我的例子:
some_num = (1)
some_tuple = (1,)
更改此行:
writer.writerow((text))
到
writer.writerow((text,))
注意逗号 :)
但为什么会这样?
而不是打破它迭代整个字符串,就好像它是单个字符的元组一样,例如
>>> for character in "this string":
... print(character)
t
h
i
s
s
t
r
i
n
g
我最近尝试抓取 http://quotes.toscrape.com/ 引号(仅在第一页)并将它们保存到 csv 文件中。我得到了一个很奇怪的结果。仅使用逗号作为分隔符。请参阅下面的屏幕截图和代码:
from bs4 import BeautifulSoup
from urllib.request import urlopen
import csv
csvfile = open('quotes.csv', 'w')
writer = csv.writer(csvfile)
writer.writerow(('text'))
def parse():
html = urlopen('http://quotes.toscrape.com/page/1/')
bs = BeautifulSoup(html, 'lxml')
quotes = bs.findAll('div', class_='quote')
for quote in quotes:
try:
text = quote.find('span', class_='text').getText(
).replace(',', '|').replace('"', '')
print(text)
writer.writerow((text))
except UnicodeEncodeError:
break
parse()
csvfile.close()
您已尝试使用带有元组的写入行,但是(奇怪的怪癖)您实际上并没有使用元组。
看我的例子:
some_num = (1)
some_tuple = (1,)
更改此行:
writer.writerow((text))
到
writer.writerow((text,))
注意逗号 :)
但为什么会这样?
而不是打破它迭代整个字符串,就好像它是单个字符的元组一样,例如
>>> for character in "this string":
... print(character)
t
h
i
s
s
t
r
i
n
g