使用 Beautiful Soup 查找 h4 标签
Find h4 tag using Beautiful Soup
我对网络抓取真的很陌生,看到了一些与我类似的问题,但这些解决方案对我不起作用。所以我正在尝试抓取这个网站:https://www.nba.com/schedule 的 h4 标签,它包含即将到来的篮球比赛的日期和时间。我正在尝试使用漂亮的汤来获取该标签,但它总是 returns 并且列表为空。这是我现在使用的代码:
result = requests.get(url)
doc = BeautifulSoup(result.text, "html.parser")
schedule = doc.find_all('h4')
我在另一个答案中看到关于 h4 标签在标签内的内容,我尝试使用 json 模块,但无法让它工作。提前感谢您的帮助!
您在页面上看到的数据是从外部 URL 加载的,因此 BeautifulSoup 看不到它。要加载数据,您可以使用以下示例:
import json
import requests
url = "https://cdn.nba.com/static/json/staticData/scheduleLeagueV2_1.json"
data = requests.get(url).json()
# uncomment to print all data:
# print(json.dumps(data, indent=4))
for g in data["leagueSchedule"]["gameDates"]:
print(g["gameDate"])
for game in g["games"]:
print(
game["homeTeam"]["teamCity"],
game["homeTeam"]["teamName"],
"-",
game["awayTeam"]["teamCity"],
game["awayTeam"]["teamName"],
)
print()
打印:
10/3/2021 12:00:00 AM
Los Angeles Lakers - Brooklyn Nets
10/4/2021 12:00:00 AM
Toronto Raptors - Philadelphia 76ers
Boston Celtics - Orlando Magic
Miami Heat - Atlanta Hawks
Minnesota Timberwolves - New Orleans Pelicans
Oklahoma City Thunder - Charlotte Hornets
San Antonio Spurs - Utah Jazz
Portland Trail Blazers - Golden State Warriors
Sacramento Kings - Phoenix Suns
LA Clippers - Denver Nuggets
10/5/2021 12:00:00 AM
New York Knicks - Indiana Pacers
Chicago Bulls - Cleveland Cavaliers
Houston Rockets - Washington Wizards
Memphis Grizzlies - Milwaukee Bucks
...and so on.
我对网络抓取真的很陌生,看到了一些与我类似的问题,但这些解决方案对我不起作用。所以我正在尝试抓取这个网站:https://www.nba.com/schedule 的 h4 标签,它包含即将到来的篮球比赛的日期和时间。我正在尝试使用漂亮的汤来获取该标签,但它总是 returns 并且列表为空。这是我现在使用的代码:
result = requests.get(url)
doc = BeautifulSoup(result.text, "html.parser")
schedule = doc.find_all('h4')
我在另一个答案中看到关于 h4 标签在标签内的内容,我尝试使用 json 模块,但无法让它工作。提前感谢您的帮助!
您在页面上看到的数据是从外部 URL 加载的,因此 BeautifulSoup 看不到它。要加载数据,您可以使用以下示例:
import json
import requests
url = "https://cdn.nba.com/static/json/staticData/scheduleLeagueV2_1.json"
data = requests.get(url).json()
# uncomment to print all data:
# print(json.dumps(data, indent=4))
for g in data["leagueSchedule"]["gameDates"]:
print(g["gameDate"])
for game in g["games"]:
print(
game["homeTeam"]["teamCity"],
game["homeTeam"]["teamName"],
"-",
game["awayTeam"]["teamCity"],
game["awayTeam"]["teamName"],
)
print()
打印:
10/3/2021 12:00:00 AM
Los Angeles Lakers - Brooklyn Nets
10/4/2021 12:00:00 AM
Toronto Raptors - Philadelphia 76ers
Boston Celtics - Orlando Magic
Miami Heat - Atlanta Hawks
Minnesota Timberwolves - New Orleans Pelicans
Oklahoma City Thunder - Charlotte Hornets
San Antonio Spurs - Utah Jazz
Portland Trail Blazers - Golden State Warriors
Sacramento Kings - Phoenix Suns
LA Clippers - Denver Nuggets
10/5/2021 12:00:00 AM
New York Knicks - Indiana Pacers
Chicago Bulls - Cleveland Cavaliers
Houston Rockets - Washington Wizards
Memphis Grizzlies - Milwaukee Bucks
...and so on.