我用python编写了一个scarper来解析网页中的一些数据。我的目的是把数据存储在字典里。我没有演示完整的表,而是尝试使用一个包含单个播放器信息的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_info
等于以下表达式(简化了一点):content
似乎只有一项。你想要的可能是:如果内容有多个项,请删除第一个代码块中的第二对
[ ... ]
相关问题 更多 >
编程相关推荐