gpt4 book ai didi

python - 网页抓取 : output CSV is messed up

转载 作者:行者123 更新时间:2023-11-30 22:45:16 25 4
gpt4 key购买 nike

此代码旨在循环遍历所有结果页面,然后循环遍历每个页面上的结果表,并从表中抓取所有数据以及表外部存储的一些信息。

但是,生成的 CSV 文件似乎没有任何合理的组织,每行的不同列中都有不同类别的信息。我所追求的是每一行包含定义的所有信息类别(日期、政党、开始日期、结束日期、选区、注册协会、候选人是否当选、候选人姓名、地址和财务代理) )。其中一些数据存储在每个页面的表格中,而其余数据(日期、政党、地区、注册协会)存储在表格外部,需要与每个页面上每个表格行中的每个候选人相关联。此外,似乎没有任何“当选”、“地址”或“财务代理人”的输出,我不确定我哪里出错了。

如果您能帮助我弄清楚如何修复我的代码以实现此输出,我将非常感激。如下:

from bs4 import BeautifulSoup
import requests
import re
import csv

url = "http://www.elections.ca/WPAPPS/WPR/EN/NC?province=-1&distyear=2013&district=-1&party=-1&pageno={}&totalpages=55&totalcount=1368&secondaryaction=prev25"

rows = []

for i in range(1, 56):
print(i)
r = requests.get(url.format(i))
data = r.text
soup = BeautifulSoup(data, "html.parser")
links = []

for link in soup.find_all('a', href=re.compile('selectedid=')):
links.append("http://www.elections.ca" + link.get('href'))

for link in links:
r = requests.get(link)
data = r.text
cat = BeautifulSoup(data, "html.parser")
header = cat.find_all('span')
tables = cat.find_all("table")[0].find_all("td")

rows.append({
#"date":
header[2].contents[0],
#"party":
re.sub("[\n\r/]", "", cat.find("legend").contents[2]).strip(),
#"start_date":
header[3].contents[0],
#"end_date":
header[5].contents[0],
#"electoral district":
re.sub("[\n\r/]", "", cat.find_all('div', class_="group")[2].contents[2]).strip(),
#"registered association":
re.sub("[\n\r/]", "", cat.find_all('div', class_="group")[2].contents[2]).strip().encode('latin-1'),
#"elected":
re.sub("[\n\r/]", "", cat.find_all("table")[0].find_all("td", headers="elected/1")[0].contents[0]).strip(),
#"name":
re.sub("[\n\r/]", "", cat.find_all("table")[0].find_all("td", headers="name/1")[0].contents[0]).strip(),
#"address":
re.sub("[\n\r/]", "", cat.find_all("table")[0].find_all("td", headers="address/1")[0].contents[0]).strip(),
#"financial_agent":
re.sub("[\n\r/]", "", cat.find_all("table")[0].find_all("td", headers="fa/1")[0].contents[0]).strip()
})

with open('scrapeOutput.csv', 'w') as f_output:
csv_output = csv.writer(f_output)
csv_output.writerows(rows)

最佳答案

我认为你的字典有点乱,你没有分配键。请记住,如果将字典转换为列表,python 会根据键按字母顺序对它们进行排序。但使用 csv 库,您可以轻松打印 csv,而无需执行所有这些操作。

所以分配键:

rows.append({
"date":
header[2].contents[0],
"party":
re.sub("[\n\r/]", "", cat.find("legend").contents[2]).strip(),
"start_date":
header[3].contents[0],
"end_date":
header[5].contents[0],
"electoral district":
re.sub("[\n\r/]", "", cat.find_all('div', class_="group")[2].contents[2]).strip(),
"registered association":
re.sub("[\n\r/]", "", cat.find_all('div', class_="group")[2].contents[2]).strip().encode('latin-1'),
"elected":
re.sub("[\n\r/]", "", cat.find_all("table")[0].find_all("td", headers="elected/1")[0].contents[0]).strip(),
"name":
re.sub("[\n\r/]", "", cat.find_all("table")[0].find_all("td", headers="name/1")[0].contents[0]).strip(),
"address":
re.sub("[\n\r/]", "", cat.find_all("table")[0].find_all("td", headers="address/1")[0].contents[0]).strip(),
"financial_agent":
re.sub("[\n\r/]", "", cat.find_all("table")[0].find_all("td", headers="fa/1")[0].contents[0]).strip()
})

然后使用DictWriter写入您的csv:

with open('scrapeOutput.csv', 'w') as f_output:
csv_output = csv.DictWriter(f_output, rows[0].keys())
csv_output.writeheader() # Write header to understand the csv
csv_output.writerows(rows)

我对此进行了测试,它可以正常工作,但请注意您的某些字段(例如地址或选举)为空:)

再见!

关于python - 网页抓取 : output CSV is messed up,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41237695/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com