Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法将输出作为格式正确的字典获取_Python_Python 3.x_Dictionary_Web Scraping - Fatal编程技术网

Python 无法将输出作为格式正确的字典获取

Python 无法将输出作为格式正确的字典获取,python,python-3.x,dictionary,web-scraping,Python,Python 3.x,Dictionary,Web Scraping,我已经用python编写了一个scaper来解析网页中的一些数据。我的目的是把数据存储在字典里。我没有演示完整的表格,而是尝试使用一个包含单个玩家信息的tr。数据正在通过,但输出的格式不是字典的样子。我们将非常感谢任何帮助,以使其准确 这是我的尝试: import requests from bs4 import BeautifulSoup URL = "https://fantasy.premierleague.com/player-list/" def get_data(link):

我已经用python编写了一个scaper来解析网页中的一些数据。我的目的是把数据存储在字典里。我没有演示完整的表格,而是尝试使用一个包含单个玩家信息的
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']}]

顺便说一句,我打算解析完整的表,但我在这里显示了一个最小部分供大家仔细观察。

player\u info
等于以下表达式(简化了一点):

内容
似乎只有一项。您想要的可能是:

 player_info = [item for item in content]

如果内容包含多个项目,请删除第一个代码块中的第二对
[…]

如果要使用嵌套列表理解,请尝试替换

[[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)")]


itmval['player\u info']=[[item.get\u text(strip=True)表示项目中的项目。选择(“td”)表示内容中的项目。选择(“table:nth of type(1)tr:nth of type(2)”)]
这将创建列表列表。所以这是意料之中的。你想把名单弄平?
[[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")]