【问题标题】:Assigning multiple values to a dictionary to write as json data?将多个值分配给字典以写入 json 数据?
【发布时间】:2018-05-26 19:13:17
【问题描述】:

我正在尝试编写一个程序来抓取我最喜欢的播客的网址。然后我想从后面的数据创建一个本地网站。

我正在尝试创建一个字典,然后可以将其写入为 json 文件,然后使用 javascript 访问该数据。

我希望字典看起来像:

{"url": "www.test.com", "text" : "Podcast 1... foo bar"}

但是,我在分配值时遇到了麻烦。到目前为止我所拥有的:

def findLinks(url):
    filename = url[-16:-4] + ".json"
    response = requests.get(url).content
    soup = BeautifulSoup(response, parseOnlyThese=SoupStrainer('a'))

    for link in soup:
        if link.has_key('href'):
            links[link.attrMap['href']] = link.getText() #Dictionary

    writeToJSON(filename, links)

【问题讨论】:

标签: python json dictionary beautifulsoup


【解决方案1】:

像这样创建字典:

    if link.has_attr('href'):
        links = {'url': link.get('href'), 'text': link.get_text()}

但是,如果您在循环中执行此操作,links 中的值将在处理每个链接时被替换,并且您最终只会将一个字典保存到文件中。因此,您可能应该改用字典列表。随时将每个字典附加到列表中:

links = []
for link in soup:
    if link.has_attr('href'):
        links.append({'url': link['href'], 'text': link.get_text()})

或者使用列表推导:

links = [{'url': link['href'], 'text': link.get_text()} for link in soup if link.has_attr('href')]

最后,将其写入 JSON 格式的文件:

writeToJSON(filename, links)

【讨论】:

    【解决方案2】:
    def findLinks(url):
        temp_list = []
        filename = url[-16:-4] + ".json"
        response = requests.get(url).content
        soup = BeautifulSoup(response, parseOnlyThese=SoupStrainer('a'))
    
        for link in soup:
            if link.has_key('href'):
              result_dict = {'url': link['href'], 'text': link.get_text()}
              temp_list.append(result_dict)
    
        json.dump(temp_list,open(filename,'w'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 2020-06-10
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多