Python New York Times Web Scaping Error(“bytes to string”)

时间:2017-02-13 14:41:48

标签: python python-2.7 python-3.x error-handling web-scraping

这是我从网上获得的代码,当我执行它时,它说出了以下错误,我是网络抓取的新手,所以完全混淆了它。 谁能告诉我我的代码出错了? 谢谢你的帮助!

from nytimesarticle import articleAPI
api = articleAPI('a0de895aa110431eb2344303c7105a9f')


articles = api.search( q = 'Obama', 
     fq = {'headline':'Obama', 'source':['Reuters','AP', 'The New York Times']}, 
     begin_date = 20111231 )


def parse_articles(articles):
    news = []
    for i in articles['response']['docs']:
        dic = {}
        dic['id'] = i['_id']
        if i['abstract'] is not None:
            dic['abstract'] = i['abstract'].encode("utf8")
        dic['headline'] = i['headline']['main'].encode("utf8")
        dic['desk'] = i['news_desk']
        dic['date'] = i['pub_date'][0:10] # cutting time of day.
        dic['section'] = i['section_name']
        if i['snippet'] is not None:
            dic['snippet'] = i['snippet'].encode("utf8")
        dic['source'] = i['source']
        dic['type'] = i['type_of_material']
        dic['url'] = i['web_url']
        dic['word_count'] = i['word_count']
        # locations
        locations = []
        for x in range(0,len(i['keywords'])):
            if 'glocations' in i['keywords'][x]['name']:
                locations.append(i['keywords'][x]['value'])
        dic['locations'] = locations
        # subject
        subjects = []
        for x in range(0,len(i['keywords'])):
            if 'subject' in i['keywords'][x]['name']:
                subjects.append(i['keywords'][x]['value'])
        dic['subjects'] = subjects   
        news.append(dic)
    return(news)

def get_articles(date,query):
    all_articles = []
    for i in range(0,100): #NYT limits pager to first 100 pages. But rarely will you find over 100 pages of results anyway.
        articles = api.search(q = query,
               fq = {'source':['Reuters','AP', 'The New York Times']},
               begin_date = date + '0101',
               end_date = date + '1231',
               sort='oldest',
               page = str(i))
        articles = parse_articles(articles)
        all_articles = all_articles + articles
    return(all_articles)

Amnesty_all = []
for i in range(1980,2014):
    print ('Processing' + str(i) + '...')
    Amnesty_year =  get_articles(str(i),'Amnesty International')
    Amnesty_all = Amnesty_all + Amnesty_year

import csv
keys = Amnesty_all[0].keys()
with open('amnesty-mentions.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(Amnesty_all)

这是我在python 3.4上运行时的输出: -

输出:

Traceback (most recent call last):
  File "/Users/niharika/Documents/nyt.py", line 7, in <module>
    begin_date = 20111231 )
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/nytimesarticle.py", line 111, in search
    API_ROOT, response_format, self._options(**kwargs), key
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/nytimesarticle.py", line 84, in _options
    v = _format_fq(v)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/nytimesarticle.py", line 69, in _format_fq
    d[k] = '"' + v + '"'
TypeError: Can't convert 'bytes' object to str implicitly
>>> 

代码来源:http://dlab.berkeley.edu/blog/scraping-new-york-times-articles-python-tutorial

2 个答案:

答案 0 :(得分:0)

错误告诉您将vbytes对象)转换为字符串显式

答案 1 :(得分:0)

基本上我从NYTimesArticleAPI/NYTimesArticleAPI/search_api.py复制了code,并将其替换为我已安装的nytimesarticle文件nytimesarticle.py

因此删除了

def _utf8_encode(self, d): ......

阻止nytimesarticle模块使用python3,在api的搜索功能上抛出TypeError:must be str,not bytes