python - 如何在beautifulsoup中找到列表的父母
问题描述
import requests
from bs4 import BeautifulSoup
url ="https://www.hltv.org/stats/matches/mapstatsid/103093/furia-vs-chaos"
headers= {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
response = requests.get(url, headers = headers)
soup = BeautifulSoup(response.content, "html.parser")
#stat_tables = soup.find_all("table", class_="stats-table")
results = {}
all_results = soup.find_all("div", class_="round-history-half")
for partial_result in all_results:
half_results = partial_result.find_all("img")
for result in half_results:
if (result["title"]):
rounds_won = result["title"].split("-")
key = int(rounds_won[0]) + int(rounds_won[1])
results[key] = result["title"]
for key in sorted(results):
print(key, results[key])
这段代码给了我比赛的所有分数,我想找到父母,比如说 print(results[4]),看看谁赢了。我不知道如何从列表中找到父母。
结果应该是
<img alt="FURIA" src="https://static.hltv.org/images/team/logo/8297" class="round-history-team" title="FURIA">
或者
Furia
解决方案
用这个,
# retrieve the parent first.
divs = soup.find_all("div", class_="round-history-team-row")
for div in divs:
parent_img_title = div.find('img', class_="round-history-team")['title']
print("Title : " + parent_img_title)
for result in div.find_all("img", class_="round-history-outcome"):
if result["title"]:
rounds_won = result["title"].split("-")
key = int(rounds_won[0]) + int(rounds_won[1])
print("Key %d" % key)
results[key] = result["title"]
输出,
Title : FURIA
Key 4
Key 5
...
Title : Chaos
Key 1
Key 2
推荐阅读
- apache-camel - Apache Camel Bindy:在第 2 行的固定长度记录末尾发现意外/未映射的字符
- c# - 最佳实践 C# REST API
- javascript - 我需要一些帮助来进行动态输入
- visual-studio - 小型转储中的不完整堆栈跟踪
- c++ - 我该如何实现一个奇怪的“类”符号
- django - 从基于类的视图中的 HTTP 方法返回响应对象
- reactjs - 如何在反应中获取键值对的值?
- sql-server - SqlException (0x80131904):无法打开登录请求的数据库“DBName”
- parse-platform - Parse - 结合 LiveQuery 更新本地 DataStore
- css - 卡片悬停动画比例背景