【发布时间】:2015-12-02 21:50:06
【问题描述】:
我目前正在学校学习 python,并且一直在玩 BeautifulSoup,它非常简单。我现在正在尝试使用 python 的 csv 模块导出列表,但它没有按照我想要的方式运行。这是我的代码:
import csv
import requests
from bs4 import BeautifulSoup
import pprint
import sys
url = 'http://www.yellowpages.com/search?search_terms=restaurants&geo_location_terms=Charleston%2C%20SC'
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html, "html.parser")
g_data = soup.find_all("div", {"class": "info"}) #this isolates the big chunks of data which houses our child tags
for item in g_data: #iterates through big chunks
try:
eateryName = (item.contents[0].find_all("a", {"class": "business-name"})[0].text)
except:
pass
print(eateryName)
with open('csvnametest.csv', "w") as csv_file:
writer = csv.writer(csv_file)
writer.writerow([eateryName])
我正在获取所有餐厅名称(作为打印功能的证据),但是当我打开 Excel 文档时,它只有列表中的姓氏而不是所有名称。我试图附加eateryName,但随后它将所有名称放在一个单元格中。在此处输入代码
【问题讨论】:
-
当你在 Python 中使用 csv 时,我建议你使用
pandas。它会让你的生活更轻松。
标签: python csv beautifulsoup