【问题标题】:output beautifulsoup data into a csv将beautifulsoup数据输出到csv
【发布时间】: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


【解决方案1】:

将行写入 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

【讨论】:

  • 那仍然将soup.title 与描述放在同一列中。我想要 2 列:标题和描述每个标题都有一个描述(这是两个打印语句的组合)。我有大约 1000 个soup.titles
  • 我在原始帖子中添加了一张照片。上面写着“这里有一堆文字”。那应该是我的两条打印线的组合。根据您的代码,事情正在将文本保存到 csv 中的每一列,并且标题没有出现。基本上我的 for 循环会遍历 50 个标题,然后获取每个标题的描述。
  • 我已经进一步编辑,我一直在覆盖错误的部分。基本上,你想要在每一行的第一列是标题:current_row = [soup.title, ''],然后你只需将其他文本添加到其他部分current_row[1] += other_text。当前版本应反映这一变化。
  • 我看不出有什么变化
  • 我添加了关于如何在 csv 的列中添加内容的说明,不确定这是否有助于您查看需要执行的操作,但此时我没有看到断开连接.
猜你喜欢
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 2017-02-20
  • 2017-06-18
  • 2021-11-16
  • 2017-11-01
相关资源
最近更新 更多