【发布时间】:2017-08-12 05:38:37
【问题描述】:
我想将我的 beautifulsoup 数据输出到包含 2 列的 csv 中:1. 标题,2. 描述
所以标题列应该有soup.Title,然后描述应该是循环中以for x in courselinks开头的打印语句......
**#This is what I tried:**
with open('newcsv.csv','wb') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow('Title')
for x in courselinks[0:3]:
data = requests.get(("http:"+x)
soup = bs(data.text)
print soup.title #This I want in the Title column
for header in soup.find_all(text='Description'):
nextNode = header.parent
while True:
nextNode = nextNode.nextSibling
if nextNode is None:
break
if isinstance(nextNode, Tag):
print (nextNode.get_text(strip=True).strip().encode('utf-8')) **#This I want in the Description column**
if isinstance(nextNode, NavigableString):
print (nextNode.strip().encode('utf-8')) **#This I want in the Description column**
if isinstance(nextNode, Tag):
if nextNode.name == "h2":
break
【问题讨论】:
-
您不想以
for x in courselink[0:3]:开头的行缩进吗? -
是的,很抱歉格式问题,它们在我的原件上缩进了
-
是的格式问题,它们在我的原始代码中。我只是想让两个打印语句写入同一个单元格。
标签: python csv beautifulsoup