r.write ('\ n') обрезает необходимые данные - PullRequest
0 голосов
/ 07 февраля 2020
import requests
from bs4 import BeautifulSoup


#get website, trick website into thinking you're using chrome.
url = 'http://www.espn.com/mlb/stats/pitching/_/sort/wins/league/al/year/2019/seasontype/2'
headers ={'User-Agent': 'Mozilla/5.0'}
res = requests.get(url, headers)

#sets soup to res and spits it out in html parsing format
soup = BeautifulSoup(res.content, 'html.parser')

#finds table from website
stats = soup.find_all('table', class_='tablehead')
stats = stats[0]

#saves the table into a text file.
with open('pitchers_stats.txt', 'w') as r:

 for row in stats.find_all('tr'):
    r.write(row.text.ljust(5))
    #delete next two lines. the program sort of works, for those trying to help me on stackOverflow.
    for cell in stats.find_all('td'):
        r.write('\n')
    # divide each row by a new line
    r.write('\n')

просто распечатывает «сортируемую передачу», и я не уверен, почему.

программа работает, как и ожидалось, удаляя строки:

for cell in stats.find_all('td'):
  r.write('\n')

^ делает это показывает следующее:.

enter image description here

1 Ответ

0 голосов
/ 07 февраля 2020

Я предполагаю, что вы пытаетесь проанализировать таблицу и разместить каждый столбец в новой строке.

Проблема в том, что вы пытаетесь проанализировать содержимое тега <tr>. Вместо этого вам следует выполнить итерацию <td> элементов внутри него.

import requests
from bs4 import BeautifulSoup


#get website, trick website into thinking you're using chrome.
url = 'http://www.espn.com/mlb/stats/pitching/_/sort/wins/league/al/year/2019/seasontype/2'
headers ={'User-Agent': 'Mozilla/5.0'}
res = requests.get(url, headers)

#sets soup to res and spits it out in html parsing format
soup = BeautifulSoup(res.content, 'html.parser')

#finds table from website
stats = soup.find_all('table', class_='tablehead')
stats = stats[0]

#saves the table into a text file.
with open('pitchers_stats.txt', 'w') as r:
 for row in stats.find_all('tr'):
    for data in row.find_all('td'):
        r.write(data.text.ljust(5))
        r.write('\n')
    r.write('\n')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...