我目前在學校學習python,並一直在玩BeautifulSoup,它一直非常簡單。我現在正嘗試使用python的csv模塊導出列表,但它不能按照我希望的方式運行。這裏是我的代碼: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但隨後它把所有的名字在一個cell.enter代碼在這裏
當你在Python中使用csv時,我建議你使用'pandas'。它會讓你的生活更輕鬆。 – burhan