美丽的Python3Howlongtobeat.com网站提取名称(和其他元素)

2024-06-01 01:47:41 发布

您现在位置:Python中文网/ 问答频道 /正文

想知道如何通过beautifulsoup提取游戏名称

我想我对它的HTML方面有问题

到目前为止,我得到的是:

from requests import get

url = 'https://howlongtobeat.com/game.php?id=38050'

response = get(url)

from bs4 import BeautifulSoup

html_soup = BeautifulSoup(response.text, 'html.parser')

game_length = html_soup.find_all('div', class_='game_times')

length = (game_length[-1].find_all({'li': '    short time_100 shadow_box'})[-1].contents[3].get_text())

print(length)

game_name = html_soup.find_all('div', class_='profile_header_game')

game = (game_name[].find({"profile_header shadow_text"})[].contents[].get_text())

print(game)

我知道长度但不知道游戏名为什么?你知道吗

对于打印(长度)打印:

31 Hours 

但对于打印(游戏)打印:

game_name = html_soup.find_all('div', class_='profile_header_game')

game = (game_name[].find({"profile_header shadow_text"})[].contents[].get_text()) File "", line 1 game = (game_name[].find({"profile_header shadow_text"})[].contents[].get_text()) ^ SyntaxError: invalid syntax

print(game) Traceback (most recent call last): File "", line 1, in NameError: name 'game' is not defined

我做错什么了?你知道吗


Tags: textnamedivgame游戏gethtmlcontents
2条回答

较短版本

game_length = html_soup.select('div.game_times li div')[-1].text
game_name = html_soup.select('div.profile_header')[0].text
developer = html_soup.find_all('strong', string='\nDeveloper:\n')[0].next_sibling

您的代码中似乎存在一些语法问题。以下是更正的版本:

from bs4 import BeautifulSoup
import requests

url = 'https://howlongtobeat.com/game.php?id=38050'
response = requests.get(url)

html_soup = BeautifulSoup(response.text, 'html.parser')
game_times_tag = html_soup.find('div', class_='game_times')

game_time_list = []
for li_tag in game_times_tag.find_all('li'):
    title = li_tag.find('h5').text.strip()
    play_time = li_tag.find('div').text.strip()

    game_time_list.append((title, play_time))

for game_time in game_time_list:
    print(game_time)

profile_header_tag = html_soup.find("div", {"class": "profile_header shadow_text"})
game_name = profile_header_tag.text.strip()
print(game_name)

相关问题 更多 >