SirSeba
SirSeba

Reputation: 151

Print certain value inside <td>

I am trying to print certain value that it's inside a <td> . The values I get from a webpage and they look like this:

  <b>General Information</b>
  <table width="400">
      <tr>
          <td>Hostname</td>
          <td>jade.nephrite.ro - Quest special | Roata Norocului</td>
      </tr>
      <tr>
          <td>Gamemode</td>
          <td>nephrite, 04 Mar 2019 14:52:55</td>
      </tr>
      <tr>
          <td>Players</td>
          <td>330 / 1000</td>
      </tr>
      <tr>
          <td>Map</td>
          <td>RO/EN</td>
      </tr>
      <tr>
          <td>Weather</td>
          <td>5</td>
      </tr>
      <tr>
          <td>Time</td>
          <td>23:00</td>
      </tr>
      <tr>
          <td>Version</td>
          <td>0.3.7-R2</td>
      </tr>
      <tr>
          <td>Password</td>
          <td>No</td>
      </tr>
  </table>

  <br />
  <b>Online Players</b>
  <br /><i>None</i>

I am trying to print only <td>330 / 1000</td> that's under <td>Players</td>. I tried many ways that I could find on google but sadly none worked for me as I don't have that much experience in python and couldn't edit the code so that works for my table.

Current code:

import requests

url = "http://crowned.ro/api/test.php"
headers = {
    'User-Agent': 'Mozilla/5.0',
}
response = requests.get(url, headers=headers)
infos = response.text
#infos = response.json()
print(infos.find("Players"))
#print(infos['[Players]'])

Upvotes: 0

Views: 237

Answers (1)

SirSeba
SirSeba

Reputation: 151

Thanks to @jon-clements, I looked thorugh BeautifulSoup4 and learned a bit how to use it. The solution is:

soup = BeautifulSoup(infos, 'html.parser')
print(soup.find('td', text='Players').find_next_sibling('td').text)

so everything looks like this now:

import requests
from bs4 import BeautifulSoup

url = "http://crowned.ro/api/test.php?sv=jade.nephrite.ro"
headers = {
    'User-Agent': 'Mozilla/5.0',
}
response = requests.get(url, headers=headers)
infos = response.text
soup = BeautifulSoup(infos, 'html.parser')
print(soup.find('td', text='Players').find_next_sibling('td').text)

Upvotes: 1

Related Questions