我目前正在学校学习python并且一直在玩BeautifulSoup并且它非常直接。我现在正在尝试使用csv模块为python导出列表,但它没有按照我想要的方式运行。这是我的代码:
:3306
我得到了所有的餐馆名称(作为打印功能的证据)但是当我打开Excel文档时,它只是列表上的姓氏而不是所有的名字。我试图附加eateryName但是它将所有名称放在一个cell.enter代码中
答案 0 :(得分:0)
你可以试试这个:
with open('csvnametest.csv', "w") as csv_file:
writer = csv.writer(csv_file)
for row in eateryName:
writer.writerow(row)
答案 1 :(得分:0)
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', "wa") as csv_file:
writer = csv.writer(csv_file)
writer.writerow([eateryName])
原因是你的写作在循环之外,所以你只写了最后一个条目,而你的写只有#34; w"只写过并且没有附加。