2017-03-20 87 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