Вытягивание текста с очищенной страницы с помощью BeautifulSoup - PullRequest
0 голосов
/ 10 мая 2019

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

Вот с чем я сейчас работаю:

import requests
from bs4 import BeautifulSoup

url = 'https://www.tsn.ca/panarin-tops-2019-free-agent-frenzy-class-1.1303592'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}

page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')

players = soup.find_all('td').text
print(players)

, который возвращает следующее:

Traceback (most recent call last):
  File "tsn.py", line 10, in <module>
    players = soup.find_all('td').text
  File "/home/debian1/.local/lib/python3.5/site-packages/bs4/element.py", line 1620, in __getattr__
    "ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'text'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?

Я также видел .get_text(), используемый в документации BS, но это возвращает ту же ошибку.

Ответы [ 4 ]

3 голосов
/ 10 мая 2019

Ваше решение было правильным. Вы получаете список значений из метода find_all(). все, что вам нужно сделать, это повторить его и получить необходимый текст. Я исправил код и выложил его ниже.

import requests
from bs4 import BeautifulSoup

url = 'https://www.tsn.ca/panarin-tops-2019-free-agent-frenzy-class-1.1303592'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}

page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')

# This is how you should have extracted the text from the ResultSet

players = [elem.text for elem in soup.find_all('td')]
print(players)
1 голос
/ 10 мая 2019

Эта ошибка означает, что вы должны выполнять итерации по каждому элементу следующим образом:

players = [item.text for item in soup.find_all('td')] # Iterate over every item and extract the text

print(players)  
print("".join(players)) # If you want all the text in one string

Надеюсь, это поможет!

1 голос
/ 10 мая 2019

find_all() вернет список всех элементов, соответствующих вашим требованиям.Даже если найден только один элемент или элемент не найден, он вернет [item] или [] соответственно.Чтобы получить текст, вам нужно будет индексировать элемент следующим образом:

players_list = soup.find_all('td')
for player in players_list:
    print(player.text)

Я использую .getText() в своих скриптах, я не уверен, работает ли .text так же или нет!

0 голосов
/ 10 мая 2019

Это рабочий скрипт:

import requests
from bs4 import BeautifulSoup

url = 'https://www.tsn.ca/panarin-tops-2019-free-agent-frenzy-class-1.1303592'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}

page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')

players = []
tbl = soup.find('table', attrs={'class':'stats-table-scrollable article-table'})
tbl_body = tbl.find('tbody')
rows = tbl_body.find_all('tr')
for row in rows:
    columns = row.find_all('td')
    columns = [c.text for c in columns]
    players.append(columns[1])
print(players)

Результат:

['Artemi Panarin', 'Erik Karlsson', 'Sergei Bobrovsky', 'Matt Duchene', 'Jeff Skinner', 'Anders Lee', 'Joe Pavelski', 'Brock Nelson', 'Tyler Myers', 'Mats Zuccarello', 'Alex Edler', 'Gustav Nyquist', 'Jordan Eberle', 'Micheal Ferland', 'Jake Gardiner', 'Ryan Dzingel', 'Kevin Hayes', 'Brett Connolly', 'Marcus Johansson', 'Braydon Coburn', 'Wayne Simmonds', 'Brandon Tanev', 'Joonas Donskoi', 'Colin Wilson', 'Ron Hainsey']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...