Как получить все мои проанализированные данные в массиве, а не в отдельных списках? - PullRequest
0 голосов
/ 14 октября 2019

Я пытаюсь разобрать список таблиц Строковый метод в конце страницы , но застрял на последнем шаге. Вот как я это сделал:

from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "https://www.w3schools.com/python/python_strings.asp"
html = urlopen(url)
soup = BeautifulSoup(html, 'lxml')
table = soup.table
rows = table.find_all('tr')
for tr in rows:
  td = tr.find_all('td')
  row = [i.text for i in td]
  print(row)

Но вот O / PI получает:

Screenshot: But here is the O/P I am getting

Как я могу получить это в массиве так, чтобымне было бы легко превратить его в df? Любое другое предложение будет оценено!

Ответы [ 2 ]

1 голос
/ 14 октября 2019

Когда я когда-либо вижу теги <table>, <tr>, <td>, я иду прямо к пандам (он использует BeautifulSoup под капотом). Он сделает за вас тяжелую работу и немного очистит:

import pandas as pd

url = "https://www.w3schools.com/python/python_strings.asp"

df = pd.read_html(url)[0]

Вывод:

print (df)
            Method                                        Description
0     capitalize()         Converts the first character to upper case
1       casefold()                    Converts string into lower case
2         center()                          Returns a centered string
3          count()  Returns the number of times a specified value ...
4         encode()           Returns an encoded version of the string
5       endswith()  Returns true if the string ends with the speci...
6     expandtabs()                    Sets the tab size of the string
7           find()  Searches the string for a specified value and ...
8         format()               Formats specified values in a string
9     format_map()               Formats specified values in a string
10         index()  Searches the string for a specified value and ...
11       isalnum()  Returns True if all characters in the string a...
12       isalpha()  Returns True if all characters in the string a...
13     isdecimal()  Returns True if all characters in the string a...
14       isdigit()  Returns True if all characters in the string a...
15  isidentifier()        Returns True if the string is an identifier
16       islower()  Returns True if all characters in the string a...
17     isnumeric()  Returns True if all characters in the string a...
18   isprintable()  Returns True if all characters in the string a...
19       isspace()  Returns True if all characters in the string a...
20       istitle()  Returns True if the string follows the rules o...
21       isupper()  Returns True if all characters in the string a...
22          join()  Joins the elements of an iterable to the end o...
23         ljust()     Returns a left justified version of the string
24         lower()                  Converts a string into lower case
25        lstrip()          Returns a left trim version of the string
26     maketrans()  Returns a translation table to be used in tran...
27     partition()  Returns a tuple where the string is parted int...
28       replace()  Returns a string where a specified value is re...
29         rfind()  Searches the string for a specified value and ...
30        rindex()  Searches the string for a specified value and ...
31         rjust()    Returns a right justified version of the string
32    rpartition()  Returns a tuple where the string is parted int...
33        rsplit()  Splits the string at the specified separator, ...
34        rstrip()         Returns a right trim version of the string
35         split()  Splits the string at the specified separator, ...
36    splitlines()  Splits the string at line breaks and returns a...
37    startswith()  Returns true if the string starts with the spe...
38         strip()            Returns a trimmed version of the string
39      swapcase()  Swaps cases, lower case becomes upper case and...
40         title()  Converts the first character of each word to u...
41     translate()                        Returns a translated string
42         upper()                  Converts a string into upper case
43         zfill()  Fills the string with a specified number of 0 ...
0 голосов
/ 14 октября 2019

Добро пожаловать в StackOverflow. Надеюсь, это поможет!

Незначительное изменение вашего кода цикла for

>>> data = []
>>> len(rows)
45
>>> for tr in rows:
...   td = tr.find_all('td')
...   row = [i.text for i in td]
...   if row:
...     data.append(row)
  1. Создана новая переменная с именем data для хранения собранной вами информации. Это объект списка типов данных (в питонах он похож на массив, но не ограничен размером, и вы можете добавлять в него все типы данных).
  2. Добавлено условие if row. Таким образом, в этой строке не найдено значений, тогда этот пустой список не добавляется в data
  3. Ниже описано, как вы создаете свой фрейм данных
>>> import pandas as pd
>>> df = pd.DataFrame(data, columns=['first', 'second'])
>>> df.head()
          first                                             second
0  capitalize()  Converts the first \r\n    character to upper ...
1    casefold()            Converts string into \r\n    lower case
2      center()                  Returns a centered \r\n    string
3       count()  Returns the number of \r\n    times a specifie...
4      encode()   Returns an encoded \r\n    version of the string
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...