python - 无法将输出作为格式正确的字典
问题描述
我在 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']}]
顺便说一句,我打算解析整个表格,但我在这里展示了一个最小的部分,供您观察。
解决方案
如果要使用嵌套列表推导,请尝试替换
[[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")]
推荐阅读
- javascript - 回调函数中的 JS 语法(nodejs、express、passport)
- python - Kivy > 线程化和使用 Spinner
- python - Spark 计划中的 Firebase 存储:要计费的项目与缺席的计费帐户相关联
- sql - 是否可以从其他表属性派生属性
- sql - 如何修复这个缓慢的 Postgres 选择查询
- ios - 如何在 MWPhotoBrowser swift iOS 中显示手机的图库
- cassandra - cassandra - 在某个条件下(在哪里)将行从一个表移动到另一个表
- mysql - 新数据库慢很多
- amazon-web-services - AWS DynamoDB 使用多个区域以获得更好的安全性?
- html - 使用包含缩略图和带有文本的 div 的百分比宽度的 Flex 项目不会随其父项调整大小?