Python BeautifulSoup Print Info in CSV
Question: I can print the information I am pulling from a site with no problem. But when
I try to place the street names in one column and the zipcodes into another
column into a CSV file that is when I run into problems. All I get in the CSV
is the two column names and every thing in its own column across the page.
Here is my code. Also I am using Python 2.7.5 and 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)   
    


Answer: The data you retrieve from the URL contains more `a` elements than `i`
elements. You must filter the `a` elements and then build pairs using the
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]))
    

Output:

    
    
    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)
    ...
    

