[英]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)
This certain code only finds one result-status element.此特定代码仅找到一个结果状态元素。 Meanwhile, I need hundreds.
同时,我需要数百个。
The output I'm looking for would be something like "L, W, L, D" depending on the data of the website of course.我正在寻找的 output 当然取决于网站的数据,类似于“L,W,L,D”。 I imported CSV because in the end I need it in that format.
我导入了 CSV 因为最后我需要它的格式。
games = soup.find_all(class_="result-status")
The result will be in list of elements with class "result-status".结果将在具有 class“结果状态”的元素列表中。
You can iterate over and extract data您可以迭代并提取数据
when you use .find()
it will return 1 (the first) element with the specific tags and attributes found in the html, even if there are 100s.当您使用
.find()
时,它将返回 1(第一个)元素,其中包含 html 中的特定标签和属性,即使有 100 个。 Like stated in the comments, you want to use find_all()
of those tags with the specific class.如评论中所述,您希望将这些标签的
find_all()
与特定的 class 一起使用。 Then you can iterate through those to get each:然后你可以遍历这些来获得每个:
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: Output:
L
D
W
D
W
...
L
L
D
W
W
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.