Web抓取以格式列出为CSV

时间:2019-01-30 15:47:14

标签: python python-3.x csv

我正在尝试从我所在地区一所大型学校的公共投票记录站点上抓取姓名和投票列表。

from tkinter import filedialog
from tkinter import *
from shutil import copy2
import os

root = Tk()
root.withdraw()

source = filedialog.askopenfilename(initialdir="/", title="Select file", filetypes=(("HTML Files","*.html"), ("all files", "*.*")))

target = 'import'
dir_parts = list(os.path.split(source))
target_dir = dir_parts[0] + target + '/' + dir_parts[1]

copy2(source, target_dir)

如果我不将其转换为列表,则.brands { ... clip-path: rectangle(0, 0, 100%, 200px); }会吐出这样的名称:

import urllib.request
from bs4 import BeautifulSoup
import csv 

poll_page = 'xurl.com'
page = urllib.request.urlopen(poll_page)
soup = BeautifulSoup(page, 'html.parser')
name_box = soup.find('div',attrs={'class': 'xyz'})
#nametest = name_box.text
name = name_box.text.splitlines()



with open('index.csv','w', newline='') as csv_file:
    thewriter = csv.writer(csv_file)
    thewriter.writerow(['Name','Vote'])
    thewriter.writerow(name)

当我转换为列表名称时,会弹出输出:

name=name_box.text

在我的CSV中,我希望名称为A列,投票为B列。我不知道将其正确解析为writerow。我可以将每个名字分成一个单独的数组,但是我需要确保每个名字都与正确的投票相对应。

编辑:我能够使用以下方法写出每个名称并在新行上投票:

Clark, Yes Bob, No Amanda, Yes

但是,下一步是用逗号分隔列,然后跳转到新行以获取新名称。再次,我的名字列表是这样的['Clark,Yes',Bob,No'],在输出的csv中,我看到:

['Clark, Yes' , 'Bob, No' , 'Amanda, Yes'] 

但是我需要在B列中添加是和否,同时保持谁投票赞成什么的一致性。有关如何执行此操作的任何想法。本质上,我需要用逗号分隔列表,然后跳到新行。

1 个答案:

答案 0 :(得分:0)

您可以通过用逗号定界符分割每个字符串元素来将列表转换为2d列表。然后将其逐行写入文件。例如

names = ['Clark, Yes' , 'Bob, No' , 'Amanda, Yes'] # This is your current output from the scraper
names =  [name.split(',') for name in names]
with open('index.csv','w', newline='') as csv_file:
    thewriter = csv.writer(csv_file)
    thewriter.writerow(['Name','Vote'])
    for name in names:
        thewriter.writerow(name)
相关问题