gpt4 book ai didi

Python BeautifulSoup 在 CSV 中打印信息

转载 作者:太空宇宙 更新时间:2023-11-04 10:42:38 24 4
gpt4 key购买 nike

我可以毫无问题地打印从网站上提取的信息。但是,当我尝试将街道名称放在一列中并将邮政编码放入另一列中并放入 CSV 文件时,这就是我遇到问题的时候。我在 CSV 文件中得到的只是两个列名,以及整个页面中它自己的列中的所有内容。这是我的代码。我也在使用 Python 2.7.5 和 Beautiful soup 4

from bs4 import BeautifulSoup
import csv
import urllib2

url="http://www.conakat.com/states/ohio/cities/defiance/road_maps/"

page=urllib2.urlopen(url)

soup = BeautifulSoup(page.read())

f = csv.writer(open("Defiance Steets1.csv", "w"))
f.writerow(["Name", "ZipCodes"]) # Write column headers as the first line

links = soup.find_all(['i','a'])

for link in links:
names = link.contents[0]
print unicode(names)

f.writerow(names)

最佳答案

您从 URL 检索的数据包含的 a 元素多于 i 元素。您必须过滤 a 元素,然后使用 Python zip buildin 构建对。

links = soup.find_all('a')
links = [link for link in links
if link["href"].startswith("http://www.conakat.com/map/?p=")]
zips = soup.find_all('i')

for l, z in zip(links, zips):
f.writerow((l.contents[0], z.contents[0]))

输出:

Name,ZipCodes
1ST ST,(43512)
E 1ST ST,(43512)
W 1ST ST,(43512)
2ND ST,(43512)
E 2ND ST,(43512)
W 2ND ST,(43512)
3 RIVERS CT,(43512)
3RD ST,(43512)
E 3RD ST,(43512)
...

关于Python BeautifulSoup 在 CSV 中打印信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19638900/

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