首页 > 解决方案 > Pandas read_html 获取 href 而不是仅针对一列的文本

问题描述

我正在尝试使用网站上的表格。我用 pandas read_html 导入时网站中的第四个表。

使用 pandas.read_html 我可以以非常简单和漂亮的方式获取数据。

我的问题是我不需要最后一列(“Arquivo”)中的“下载”文本,而是需要下载的 href 链接。

有人可以帮我实现这个例外吗?

我已经看到了一些答案(例如:HTML table to pandas table: Info inside html tags),但在我的情况下我无法实现。

这是我的代码:

import pandas as pd
data = (pd.read_html('http://sisweb.tesouro.gov.br/apex/f?p=2501:2::::2::')[3])
print(df) #this way I print the table with 'Download' text.

第二次尝试:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options() #I pretend to use headless, but I did not activate in this example. 
options.add_argument('--headless')
options.add_argument('--disable-gpu') 

driver = webdriver.Chrome()
driver.get('http://sisweb.tesouro.gov.br/apex/f?p=2501:2::::2::')

bsobj = bs(driver.page_source, 'lxml')

tabela_geral = bsobj.findAll('table', {'class':'table table-striped'})

#this returns to me all the tables I want to work with. is this case, the table in the first (0)

import lxml.html as LH

table = LH.fromstring(str(tabela_geral[0])) #getting just the first return from selenium.

for df in pd.read_html(str(tabela_geral[0])):
    df['Arquivo'] = table.xpath('//tr/td/a/@href')
    print(df) #this returns me an error.

卡车。

ps:MacOS High Sierra / Python 3.6

标签: pythonpandasweb-scraping

解决方案


推荐阅读