2017-03-20 85 views
1

我想我的輸出數據beautifulsoup與2列的CSV:1.標題,背景輸出beautifulsoup數據到CSV

所以標題欄應該有soup.Title然後描述應該是print語句是在與開始在courselinks X環......

**#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 

這就是我想要的...... enter image description here

+0

難道你不想要以'courselink [0:3]:'爲縮進的''開頭的行嗎? –

+0

對不起格式問題,他們縮進我的原始 – user6754289

+0

是格式化問題,他們在我的原始代碼。我只是想讓兩個打印語句寫入同一個單元格。 – user6754289

回答

0

當寫一行到CSV,你只是寫數組或列表中的文件。列表或數組中的每個值都是該行中的一個值。如果你想在第一列中的數組中的第一個項目,你把它放在第一位,0索引。該行中的每個後續項目都是數組/列表中的後續索引。

for x in courselinks[0:3]: 
    data = requests.get(("http:"+x) 
    soup = bs(data.text) 
    current_row = [soup.title,''] #This I want in the Title column 
    for header in soup.find_all(text='Description'): 
     current_row[1] = '' 
     nextNode = header.parent 
     while True: 
      nextNode = nextNode.nextSibling 
      if nextNode is None: 
       writer.writerow(current_row) 
       break 
      if isinstance(nextNode, Tag): 
       current_row[1] += nextNode.get_text(strip=True).strip().encode('utf-8') **#This I want in the Description column** 
      if isinstance(nextNode, NavigableString): 
       current_row[1] += nextNode.strip().encode('utf-8') **#This I want in the Description column** 
      if isinstance(nextNode, Tag): 
       if nextNode.name == "h2": 
        writer.writerow(current_row) 
        break 
+0

這仍然把湯.title與描述相同的列。我想要2列:標題和說明每個標題有一個描述(這是兩個打印語句的組合)。我有大約1000湯soup.titles – user6754289

+0

沒有,這仍然無法正常工作,儘管它更接近! – user6754289

+0

我已將照片添加到原始帖子。它在哪裏寫着'一堆文字'。這應該是我的兩條印刷線的組合。根據你的代碼,事情正在將文本保存到csv中的每一列,並且標題沒有出現。基本上我的for循環是通過50個標題,然後得到他們每個人的描述。 – user6754289