首页 > 解决方案 > 无法将输出作为格式正确的字典

问题描述

我在 python 中编写了一个爬虫来解析网页中的一些数据。我的意图是将数据存储在字典中。我没有展示完整的桌子,而是尝试了一张tr包含单个玩家信息的单曲。数据正在通过,但输出的格式不是字典的样子。任何有助于使其准确的帮助将不胜感激。

这是我的尝试:

import requests
from bs4 import BeautifulSoup

URL = "https://fantasy.premierleague.com/player-list/"

def get_data(link):
    res = requests.get(link,headers={"User-Agent":"Mozilla/5.0"})
    soup = BeautifulSoup(res.text,"lxml")
    data = []
    for content in soup.select("div.ism-container"):
        itmval = {}
        itmval['name'] = content.select_one("h2").text
        itmval['player_info'] = [[item.get_text(strip=True) for item in items.select("td")] for items in content.select(" table:nth-of-type(1) tr:nth-of-type(2)")]
        data.append(itmval)

    print(data)

if __name__ == '__main__':
    get_data(URL)

我的输出:

[{'name': 'Goalkeepers', 'player_info': [['De Gea', 'Man Utd', '161', '£5.9']]}]

我期望的输出:

[{'name': 'Goalkeepers', 'player_info': ['De Gea', 'Man Utd', '161', '£5.9']}]

顺便说一句,我打算解析整个表格,但我在这里展示了一个最小的部分,供您观察。

标签: pythonpython-3.xdictionaryweb-scraping

解决方案


如果要使用嵌套列表推导,请尝试替换

[[item.get_text(strip=True) for item in items.select("td")] for items in content.select(" table:nth-of-type(1) tr:nth-of-type(2)")]

[item.get_text(strip=True) for items in content.select(" table:nth-of-type(1) tr:nth-of-type(2)") for item in items.select("td")]

推荐阅读