簡體   English   中英

如何使用 python 查找所有相同類型的元素

[英]How to find all elements of the same type with python

import requests
from bs4 import BeautifulSoup
import csv

source = requests.get("https://www.11v11.com/teams/arsenal/tab/opposingTeams/opposition/Chelsea/")

soup = BeautifulSoup(source.text, 'lxml')
print(soup.prettify())
games = soup.find(class_="result-status")
print(games.text)

此特定代碼僅找到一個結果狀態元素。 同時,我需要數百個。

我正在尋找的 output 當然取決於網站的數據,類似於“L,W,L,D”。 我導入了 CSV 因為最后我需要它的格式。

games = soup.find_all(class_="result-status")

結果將在具有 class“結果狀態”的元素列表中。
您可以迭代並提取數據

當您使用.find()時,它將返回 1(第一個)元素,其中包含 html 中的特定標簽和屬性,即使有 100 個。 如評論中所述,您希望將這些標簽的find_all()與特定的 class 一起使用。 然后你可以遍歷這些來獲得每個:

import requests
from bs4 import BeautifulSoup
import csv
source = requests.get("https://www.11v11.com/teams/arsenal/tab/opposingTeams/opposition/Chelsea/")

soup = BeautifulSoup(source.text, 'lxml')
print(soup.prettify())
games = soup.find_all(class_="result-status")
for game in games:
    print(game.text)

Output:

L
D
W
D
W
...
L
L
D
W
W

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM