[英]How to show data one word one cell rather than one character one cell in csv_file?
我练习从网站爬网数据。 这是网站: https : //delicious-fruit.com/ratings/full.php?q=ALL
我的主要目标是收集游戏名称,难度,等级,等级编号,然后使用csv保存文件。 格式是一个单词一个单元格,四个单词一个换行。
当我尝试保存文件时,发生了问题。 文件显示一个字符一个单元格,而不显示一个单词一个单元格。 结果
我认为问题是“ for循环”的影响,但不知道要解决它。 你能给我一些建议吗? 我会很感激。
我试图使用另一个变量来存储数据并将其放入“ writerows”函数中,但结果保持不变。
from bs4 import BeautifulSoup
import requests
import csv
source = requests.get('https://delicious-fruit.com/ratings/full.php?q=ALL').text
soup= BeautifulSoup(source, 'lxml')
with open ('cms_scrape.csv', 'w', errors='ignore') as csv_file:
writer = csv.writer(csv_file)
table = soup.find('tbody')
table_rows = table.find_all('tr')
for tr in table_rows:
td = tr.find_all('td')
writer.writerows([td[0].text, td[1].text, td[2].text, td[3].text])
csv_file.close()
您正在使用写行,如果要在单行中写入列表,则将写多行,您需要使用写行,请参见以下示例
from bs4 import BeautifulSoup
import requests
import csv
source = requests.get('https://delicious-fruit.com/ratings/full.php?q=ALL').text
soup= BeautifulSoup(source, 'lxml')
with open ('d:\\cms_scrape.csv', 'wb') as csv_file:
writer = csv.writer(csv_file)
table = soup.find('tbody')
table_rows = table.find_all('tr')
for tr in table_rows:
td = tr.find_all('td')
try:
texts = [str(td1.text).strip() for td1 in td]
writer.writerow(texts)
except Exception as e:
print "error while writing this row %s"%td
csv_file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.