AlJohri / craigslist

MIT License
2 stars 3 forks source link

TypeError: write() argument must be str, not JSONSearchPost #14

Closed Ginny47 closed 4 years ago

Ginny47 commented 5 years ago

Could anyone help with printing JSONSearchPost in txt or csv file format?

import craigslist, csv, time
timestr = time.strftime("%Y%m%d")

file = open('craigslist_sfbayarea_%s.txt'%timestr, 'w', newline='', encoding='utf-8')

# writer = csv.writer(csvfile, delimiter=',', lineterminator='\n')
# writer.writerow(["ListID"] + ["Title"] + ["URL"] + ["Category_ID"]+ ["Thumbnail"]+ ["Longitude"]+ ["Latitude"]+ ["Date"]+ ["Price"]+ ["Bedrooms"])

for post in craigslist.search('sfbay', 'apa', postal=95033, search_distance=1):
    print(post)

    # print(np.array(post))
    # new_post = post.strip('JSONSearchPost(').strip(')')

    # print(new_post)
    file.write(post)

file.close()
# craiglist posts expire. replace the url below with something current
post = craigslist.get('https://sfbay.craigslist.org/sby/apa/d/los-gatos-move-in-special-1st-month/7028088749.html')
AlJohri commented 5 years ago

hi @Ginny47, here's a minimal example that works for me:

import csv
import craigslist

from craigslist._search.jsonsearch import JSONSearchPost

with open('craigslist_sfbayarea.txt', 'w') as f:
    writer = csv.DictWriter(f, fieldnames=JSONSearchPost._fields)
    for post in craigslist.search('sfbay', 'apa', postal=95033, search_distance=1):
        print(post)
        writer.writerow(post._asdict())

I think in particular you were looking for the post._asdict() method.