Хранение табличных значений в переменные с BeautifulSoup - PullRequest
0 голосов
/ 05 марта 2020

Я разбирал эту таблицу на форуме, и у меня возникли трудности с сохранением значений каждой строки в переменные.

Каждая строка имеет идентификатор, имя, редкость и тип. Я думал, что переменная строки в моей программе была списком, к которому можно получить доступ по индексу, но оказалось, что это не так, поскольку он дает мне ошибку «список индексов вне диапазона».

What I'm trying to achieve

Вот код:

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = "https://yugioh.fandom.com/wiki/Legend_of_Blue_Eyes_White_Dragon"

html = urlopen(url).read() 
soup = BeautifulSoup(html)

title = soup.find("h2", {"class": "pi-item pi-item-spacing pi-title"})
print(title.text)

table = soup.find(id="Top_table") 
table_rows = table.find_all("tr")

for tr in table_rows:           #   for each row  
    td = tr.find_all('td')      #   find all cells
    row = [i.text for i in td]  #   row = all cells from row combined (I thought this is a list that can be accessed by index??)

    id = row[0]         #this is the ROW giving me the problem, turns out can't be accessed by index :c
    name = row[1]
    rarity = row[2]
    cardType = row[3]

    print(row)

Ответы [ 2 ]

2 голосов
/ 05 марта 2020

Первая строка в table_rows - это строка заголовка. В строке заголовка нет тд, поэтому в строке нет нужных вам данных. Я добавил простой пропуск любой строки, содержащей менее 4-х элементов.

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = "https://yugioh.fandom.com/wiki/Legend_of_Blue_Eyes_White_Dragon"

html = urlopen(url).read() 
soup = BeautifulSoup(html)


title = soup.find("h2", {"class": "pi-item pi-item-spacing pi-title"})
print(title.text)

table = soup.find(id="Top_table") 
table_rows = table.find_all("tr")

for tr in table_rows:           #   for each row  
    td = tr.find_all('td')      #   find all cells
    if len(td) < 4:
        continue
    row = [i.text for i in td]  #   row = all cells from row combined (I thought this is a list that can be accessed by index??)
    id = row[0]         #this is the ROW giving me the problem, turns out can't be accessed by index :c
    name = row[1]
    rarity = row[2]
    cardType = row[3]

    print(row)

Возвращает следующее

['LOB-EN000', '"Tri-Horned Dragon"', 'Secret Rare', 'Normal Monster']
['LOB-EN001', '"Blue-Eyes White Dragon"', 'Ultra Rare', 'Normal Monster']
['LOB-EN002', '"Hitotsu-Me Giant"', 'Common', 'Normal Monster']
['LOB-EN003', '"Flame Swordsman"', 'Super Rare', 'Fusion Monster']
['LOB-EN004', '"Skull Servant"', 'Common', 'Normal Monster']
['LOB-EN005', '"Dark Magician"', 'Ultra Rare', 'Normal Monster']
['LOB-EN006', '"Gaia The Fierce Knight"', 'Ultra Rare', 'Normal Monster']
...
1 голос
/ 05 марта 2020

Я думаю, что более быстрым и простым подходом было бы получить таблицы HTML непосредственно из pandas, а затем создать фрейм данных. Вот моя версия ниже: -

import requests
import pandas as pd
url = 'https://yugioh.fandom.com/wiki/Legend_of_Blue_Eyes_White_Dragon'
html = requests.get(url, verify=False).content
df_list = pd.read_html(html)
df = df_list[-6]
print(df)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...