extract href using pandas read_html

Viewed 8549

As a part of my job, I need to check this page for specific documents regularly. What I found was that I could use pandas' method read_html to successfully read the table into dataframe (which is handy as I could easily query specific documents by the keywords). The problem I have now is that this method cannot parse links that I need, and saves plain text instead (specifically I'm referring to the second columns which have numbers like '1682/0/15-19').

The code I came up with was very simple:

import pandas as pd

df = pd.read_html('http://www.vru.gov.ua/act_list')[0]

Which gives me a dataframe with all info I need except for the links.

Is it possible to somehow get links instead of plain text, and if so, how could I do it?

I know that had I used Requests and BeautifulSoup libraries, it would have been possible to get href links, but I don't know BeautifulSoup library good enough to do it. Any tips or should I just learn BeautifulSoup?

2 Answers

You can find tutorials by a quick google search. You'll essential iterating through the tags to compile a list, then turn the list of data into a dataframe:

You could also just pull the table as you did with read_html(), but you'll still need to go back and get the html links (see option 2 below):

import pandas as pd
import requests
from bs4 import BeautifulSoup


url = 'http://www.vru.gov.ua/act_list'



response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table')

records = []
columns = []
for tr in table.findAll("tr"):
    ths = tr.findAll("th")
    if ths != []:
        for each in ths:
            columns.append(each.text)
    else:
        trs = tr.findAll("td")
        record = []
        for each in trs:
            try:
                link = each.find('a')['href']
                text = each.text
                record.append(link)
                record.append(text)
            except:
                text = each.text
                record.append(text)
        records.append(record)

columns.insert(1, 'Link')
df = pd.DataFrame(data=records, columns = columns)

Option 2:

import pandas as pd
import requests
from bs4 import BeautifulSoup

url = 'http://www.vru.gov.ua/act_list'
df = pd.read_html(url)[0]

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table')

links = []
for tr in table.findAll("tr"):
    trs = tr.findAll("td")
    for each in trs:
        try:
            link = each.find('a')['href']
            links.append(link)
        except:
            pass

df['Link'] = links

Output:

print (df.to_string())
     №                             Link           Номер Вид документу Дата прийняття                                    Назва документу Примiтки
0    1  http://www.vru.gov.ua/act/18641    1682/0/15-19       Рішення     20-06-2019  Про звільнення Бурана О.М. з посади судді Мали...         
1    2  http://www.vru.gov.ua/act/18643    1684/0/15-19        Ухвала     20-06-2019  Про задоволення заяви члена Вищої ради правосу...         
2    3  http://www.vru.gov.ua/act/18644    1685/0/15-19        Ухвала     20-06-2019  Про відмову у задоволенні заяви адвоката Рохма...         
3    4  http://www.vru.gov.ua/act/18649    1690/0/15-19        Ухвала     20-06-2019  Про продовження строку розгляду скарги судді Х...         
4    5  http://www.vru.gov.ua/act/18650    1691/0/15-19       Рішення     20-06-2019  Про нагородження заохочувальною відзнакою Вищо...         
5    6  http://www.vru.gov.ua/act/18651    1692/0/15-19       Рішення     20-06-2019  Про інформацію робочої групи Вищої ради правос...         
6    7  http://www.vru.gov.ua/act/18619  1660/3дп/15-19        Ухвала     19-06-2019  Про відкриття дисциплінарної справи стосовно с...         
7    8  http://www.vru.gov.ua/act/18620  1661/3дп/15-19        Ухвала     19-06-2019  Про відмову у відкритті дисциплінарних справ з...         
8    9  http://www.vru.gov.ua/act/18624  1665/3дп/15-19        Ухвала     19-06-2019  Прo задоволення заяви члена Третьої Дисципліна...         
9   10  http://www.vru.gov.ua/act/18626  1667/3дп/15-19        Ухвала     19-06-2019  Прo задоволення заяви члена Третьої Дисципліна...         
10  11  http://www.vru.gov.ua/act/18627  1668/3дп/15-19        Ухвала     19-06-2019  Про відмову у відкритті дисциплінарних справ з...         
11  12  http://www.vru.gov.ua/act/18628  1669/3дп/15-19        Ухвала     19-06-2019  Про відмову у відкритті дисциплінарних справ з...         
12  13  http://www.vru.gov.ua/act/18635  1676/2дп/15-19        Ухвала     19-06-2019  Про відкриття дисциплінарної справи стосовно с...         
13  14  http://www.vru.gov.ua/act/18638  1679/2дп/15-19        Ухвала     19-06-2019  Про відмову у відкритті дисциплінарної справи ...         
14  15  http://www.vru.gov.ua/act/18639  1680/2дп/15-19        Ухвала     19-06-2019  Про відмову у відкритті дисциплінарних справ з...         
15  16  http://www.vru.gov.ua/act/18640  1681/2дп/15-19        Ухвала     19-06-2019  Про відмову у відкритті дисциплінарних справ з...         
16  17  http://www.vru.gov.ua/act/18607    1648/0/15-19       Рішення     18-06-2019  Про звільнення Лучко О.О. з посади судді Івано...         
17  18  http://www.vru.gov.ua/act/18608    1649/0/15-19        Ухвала     18-06-2019  Про залишення без розгляду заяви Лазаренко В.В...         
18  19  http://www.vru.gov.ua/act/18609    1650/0/15-19        Ухвала     18-06-2019  Про залишення без розгляду подання Третьої Дис...         
19  20  http://www.vru.gov.ua/act/18610    1651/0/15-19        Ухвала     18-06-2019  Про залишення без розгляду подання Другої Дисц...         
20  21  http://www.vru.gov.ua/act/18615    1656/0/15-19       Рішення     18-06-2019  Про затвердження висновків членів Вищої ради п...         
21  22  http://www.vru.gov.ua/act/18586    1627/0/15-19       Рішення     13-06-2019  Про звільнення Римлянської Г.О.               ...         
22  23  http://www.vru.gov.ua/act/18589    1630/0/15-19       Рішення     13-06-2019  Про затвердження висновку члена Вищої ради пра...         
23  24  http://www.vru.gov.ua/act/18590    1631/0/15-19       Рішення     13-06-2019                   Про призначення Максимішина С.Т.         
24  25  http://www.vru.gov.ua/act/18591    1632/0/15-19       Рішення     13-06-2019                     Про призначення Гавришука О.М.   

This available now in Pandas 1.5.0+ using the extract_links parameter.

extract_links - possible options: {None, “all”, “header”, “body”, “footer”}

Table elements in the specified section(s) with tags will have their href extracted.

  • Documentation

  • Example

    html_table = """
    <table>
    <tr>
      <th>GitHub</th>
    </tr>
    <tr>
      <td><a href="https://github.com/pandas-dev/pandas">pandas</a> 
    </td>
    </tr>
    </table>
    """
    
    # this will get you https://github.com/pandas-dev/pandas
    df = pd.read_html(
      html_table,
      extract_links="all"
    )[0]
    
Related