<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          用 Pandas 讀寫網(wǎng)頁中的 HTML 表格數(shù)據(jù)

          共 6219字,需瀏覽 13分鐘

           ·

          2020-12-28 10:18

          介紹
          超文本標(biāo)記語言(HTML)是用于構(gòu)建網(wǎng)頁的標(biāo)準(zhǔn)標(biāo)記語言。我們可以使用HTML的標(biāo)簽來呈現(xiàn)表格數(shù)據(jù)。Pandas 數(shù)據(jù)分析庫提供了read_html()to_html()之類的功能,因此我們可以將數(shù)據(jù)導(dǎo)入和導(dǎo)出到DataFrames。
          在本文中,我們將學(xué)習(xí)如何從HTML文件讀取表格數(shù)據(jù)并將其加載到Pandas DataFrame中。我們還將學(xué)習(xí)如何將數(shù)據(jù)從Pandas DataFrame寫入HTML文件。
          讀取HTML
          我們可以使用read_html()函數(shù)讀取HTML文件的表。此函數(shù)將HTML文件的表作為Pandas DataFrames讀取。它可以從文件或URL中讀取。
          從文件中讀取HTML數(shù)據(jù)
          在本節(jié)中,我們將使用一組輸入數(shù)據(jù)。一個(gè)包含編程語言及其創(chuàng)建年份的表。另一個(gè)表中有土地面積及其成本(美元)。
          將以下HTML內(nèi)容保存在名為table_data.html的文件中:
          html>
          <html?lang="en">

          <head>
          ??<meta?charset="UTF-8">
          ??<title>Table?Datatitle>
          head>

          <body>
          ??<table>
          ????<thead>
          ??????<tr>
          ????????<th>Programming?Languageth>
          ????????<th>Creatorth>
          ????????<th>Yearth>
          ??????tr>
          ????thead>
          ????<tbody>
          ??????<tr>
          ????????<td>Ctd>
          ????????<td>Dennis?Ritchietd>
          ????????<td>1972td>
          ??????tr>
          ??????<tr>
          ????????<td>Pythontd>
          ????????<td>Guido?Van?Rossumtd>
          ????????<td>1989td>
          ??????tr>
          ??????<tr>
          ????????<td>Rubytd>
          ????????<td>Yukihiro?Matsumototd>
          ????????<td>1995td>
          ??????tr>
          ????tbody>
          ??table>
          ??<table>
          ????<thead>
          ??????<tr>
          ????????<th>
          ??????????Area?(sq.ft)
          ????????th>
          ????????<th>
          ??????????Price?(USD)
          ????????th>
          ??????tr>
          ????thead>
          ????<tbody>
          ??????<tr>
          ????????<td>
          ??????????12000
          ????????td>
          ????????<td>
          ??????????500
          ????????td>
          ??????tr>
          ??????<tr>
          ????????<td>
          ??????????32000
          ????????td>
          ????????<td>
          ??????????700
          ????????td>
          ??????tr>

          ????tbody>
          ??table>
          body>

          html>
          Pandas 需要另一個(gè)名為lxml的庫的幫助來解析HTML和XML文件。為了使read_html()函數(shù)正常工作,您需要安裝lxml:
          $?pip?install?lxml
          一旦安裝了lmxl,我們就可以使用read_html()函數(shù)。它返回一個(gè)DataFrames列表,其中每個(gè)DataFrame是給定HTML文件的整個(gè)表元素。我們通過索引列表將每個(gè)表作為DataFrame進(jìn)行讀取。
          下面的代碼演示了read_html()函數(shù)從HTML文件讀取表的使用:
          import?pandas?as?pd

          tables?=?pd.read_html('table_data.html')
          print('Tables?found:',?len(tables))
          df1?=?tables[0]??#?Save?first?table?in?variable?df1
          df2?=?tables[1]??#?Saving?next?table?in?variable?df2

          print('First?Table')
          print(df1)
          print('Another?Table')
          print(df2)
          注意:雖然您需要安裝lxml,但無需將其導(dǎo)入程序中即可使Pandas正常工作。
          在Python解釋器上運(yùn)行以上代碼將產(chǎn)生以下輸出:
          Tables?found:?2
          First?Table
          ??Programming?Language?????????????Creator??Year
          0????????????????????C??????Dennis?Ritchie??1972
          1???????????????Python????Guido?Van?Rossum??1989
          2?????????????????Ruby??Yukihiro?Matsumoto??1995
          Another?Table
          ???Area?(sq.ft)??Price?(USD)
          0?????????12000??????????500
          1?????????32000??????????700
          從URL讀取HTML數(shù)據(jù)
          正如我們從HTML文件中讀取表元素一樣,我們也可以使用read_html()將HTML網(wǎng)頁中的表元素讀取到DataFrame中。我們將提供以下URL:
          read_html('https://en.wikipedia.org/wiki/Python_(programming_language)')
          它將返回一個(gè)DataFrames列表,其中每個(gè)DataFrame代表給定URL中的一個(gè)表元素。
          以下是使用Pandas從網(wǎng)站URL讀取表格元素的示例代碼:
          import?pandas?as?pd

          tables?=?pd.read_html('https://en.wikipedia.org/wiki/Python_(programming_language)')
          print('Tables?found:',?len(tables))
          df1?=?tables[0]??#?Save?first?table?in?variable?df1
          print('First?Table')
          print(df1.head())??#?To?print?first?5?rows
          如果我們成功運(yùn)行了上面的代碼,我們可以看到以下輸出:
          Tables?found:?10
          First?Table
          ????????????????0??????????????????????????????????????????????????1
          0?????????????NaN????????????????????????????????????????????????NaN
          1????????Paradigm??Multi-paradigm:?functional,?imperative,?object...
          2?????Designed?by???????????????????????????????????Guido?van?Rossum
          3???????Developer?????????????????????????Python?Software?Foundation
          4??First?appeared??????????????????????????????1991;?29?years?ago[1]
          從需要身份驗(yàn)證的URL讀取HTML數(shù)據(jù)
          現(xiàn)在我們知道可以從網(wǎng)站上讀取表格元素。但是,當(dāng)站點(diǎn)需要身份驗(yàn)證時(shí),代碼會(huì)遇到以下異常:
          raise?HTTPError(req.full_url,?code,?msg,?hdrs,?fp)
          urllib.error.HTTPError:?HTTP?Error?401:?UNAUTHORIZED
          要從此類URL讀取數(shù)據(jù),我們將使用請(qǐng)求模塊。您可以使用pip安裝它:
          $?pip?install?requests
          現(xiàn)在,如果站點(diǎn)需要身份驗(yàn)證,我們將使用請(qǐng)求庫中的get()方法向網(wǎng)站URL發(fā)出請(qǐng)求,同時(shí)提供可選的auth參數(shù)。
          此方法從網(wǎng)頁返回響應(yīng)對(duì)象。我們可以檢查狀態(tài)碼(以確保內(nèi)容肯定存在)并從響應(yīng)對(duì)象獲取文本,然后將表轉(zhuǎn)換為DataFrame。
          讓我們看一個(gè)使用請(qǐng)求獲取需要身份驗(yàn)證的數(shù)據(jù)的示例。為此,我們使用https://httpbin.org
          import?requests

          r?=?requests.get('https://httpbin.org/basic-auth/john/johnspassword',?auth=('john',?'johnspassword'))

          print(r.status_code)
          print(r.text)
          執(zhí)行上面的代碼后,我們可以看到以下輸出:
          200
          {
          ??"authenticated":?true,?
          ??"user":?"john"
          }
          這表明我們成功訪問了經(jīng)過身份驗(yàn)證的URL的網(wǎng)頁內(nèi)容。但是,此網(wǎng)站僅包含JSON數(shù)據(jù),我們需要HTML表格元素作為DataFrames。
          讓我們繼續(xù)使用以前的URL,并使用請(qǐng)求將HTML表讀取為DataFrames。與以前的站點(diǎn)是公共站點(diǎn)時(shí)相比,訪問經(jīng)過身份驗(yàn)證的內(nèi)容的步驟是相同的。
          得到響應(yīng)后,可以將r.text傳遞給read_html()方法。和往常一樣,我們將獲得它包含為DataFrames的表的列表:
          import?pandas?as?pd
          import?requests

          #?Can?use?auth?parameter?for?authenticated?URLs
          r?=?requests.get('https://en.wikipedia.org/wiki/Python_(programming_language)',
          ?????????????????auth=('john',?'johnspassword'))
          tables?=?pd.read_html(r.text)
          print('Tables?found:',?len(tables))
          df1?=?tables[0]
          print('First?Table')
          print(df1.head())
          運(yùn)行此代碼將生成以下輸出:
          Tables?found:?10
          First?Table
          ????????????????0??????????????????????????????????????????????????1
          0?????????????NaN????????????????????????????????????????????????NaN
          1????????Paradigm??Multi-paradigm:?functional,?imperative,?object...
          2?????Designed?by???????????????????????????????????Guido?van?Rossum
          3???????Developer?????????????????????????Python?Software?Foundation
          4??First?appeared??????????????????????????????1991;?29?years?ago[1]
          用Python的Pandas編寫HTML表
          我們已經(jīng)成功地從HTML表中讀取了數(shù)據(jù)。讓我們?cè)贖TML文件中編寫Pandas DataFrame。這可以通過使用to_html()方法來實(shí)現(xiàn)。
          to_html()采用要將數(shù)據(jù)導(dǎo)出到的文件的路徑。如果不提供絕對(duì)路徑,則會(huì)保存相對(duì)于當(dāng)前目錄的文件。
          您可以將DataFrame導(dǎo)出到HTML表,如下所示:
          import?pandas?as?pd

          df?=?pd.DataFrame({'A':?[1,?2],?'B':?[3,?4]})
          df.to_html('write_html.html')
          此代碼將在當(dāng)前目錄中生成以下文件write_html.html
          <table?border="1"?class="dataframe">
          ??<thead>
          ????<tr?style="text-align:?right;">
          ??????<th>th>
          ??????<th>Ath>
          ??????<th>Bth>
          ????tr>
          ??thead>
          ??<tbody>
          ????<tr>
          ??????<th>0th>
          ??????<td>1td>
          ??????<td>3td>
          ????tr>
          ????<tr>
          ??????<th>1th>
          ??????<td>2td>
          ??????<td>4td>
          ????tr>
          ??tbody>
          table>
          請(qǐng)注意,導(dǎo)出不是整個(gè)HTML文檔,而是HTML表本身。
          用Python的Pandas編寫樣式化的HTML表
          如我們所見,默認(rèn)情況下,表格邊框?yàn)?,對(duì)齊方式正確,并且在
          標(biāo)記的標(biāo)記中。
          讓我們嘗試將標(biāo)題文本對(duì)齊到中心并查看結(jié)果:
          import?pandas?as?pd

          df?=?pd.DataFrame({'A':?[1,?'AAA'],?'B':?['BBB',?4]})
          df.to_html('write_html.html',?justify='center')

          上面的代碼創(chuàng)建的表如下所示:

          <table?border="1"?class="dataframe">
          ??<thead>
          ????<tr?style="text-align:?center;">
          ??????<th>th>
          ??????<th>Ath>
          ??????<th>Bth>
          ????tr>
          ??thead>
          ??<tbody>
          ????<tr>
          ??????<th>0th>
          ??????<td>1td>
          ??????<td>BBBtd>
          ????tr>
          ????<tr>
          ??????<th>1th>
          ??????<td>AAAtd>
          ??????<td>4td>
          ????tr>
          ??tbody>
          table>
          現(xiàn)在,表格標(biāo)題的文本與中心對(duì)齊。
          結(jié)論
          在本教程中,我們學(xué)習(xí)了如何使用Pandas DataFrames導(dǎo)入和導(dǎo)出HTML表數(shù)據(jù)。我們從文件以及從網(wǎng)頁URL加載HTML表數(shù)據(jù)。對(duì)于經(jīng)過身份驗(yàn)證的URL,我們使用了請(qǐng)求模塊來對(duì)站點(diǎn)數(shù)據(jù)進(jìn)行身份驗(yàn)證和檢索,然后將響應(yīng)文本傳遞到read_html()函數(shù)中。
          我們還使用to_html()函數(shù)將 Pandas DataFrame 編寫為HTML文件。然后,我們通過傳遞一些可選參數(shù)(例如indexborderjustify)來對(duì)生成的表進(jìn)行樣式設(shè)置。這使得以呈現(xiàn)方式寫入DataFrame的數(shù)據(jù)變得容易。


          更多閱讀



          5分鐘掌握在 Cython 中使用 C++


          5 分鐘掌握 Python 中常見的配置文件


          5 分鐘掌握 Python 中的 Hook 鉤子函數(shù)

          特別推薦





          點(diǎn)擊下方閱讀原文加入社區(qū)會(huì)員

          瀏覽 45
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          標(biāo)記中也具有DataFrame索引。我們可以通過提供一些可選參數(shù)來更改此默認(rèn)結(jié)構(gòu)。
          隱藏索引
          如果我們不想在表輸出中包括索引,可以在to_html()中設(shè)置index = False
          import?pandas?as?pd

          df?=?pd.DataFrame({'A':?[1,?2],?'B':?[3,?4]})
          df.to_html('write_html.html',?index=False)
          此代碼產(chǎn)生具有以下內(nèi)容的write_html.html文件:
          <table?border="1"?class="dataframe">
          ??<thead>
          ????<tr?style="text-align:?right;">
          ??????<th>Ath>
          ??????<th>Bth>
          ????tr>
          ??thead>
          ??<tbody>
          ????<tr>
          ??????<td>1td>
          ??????<td>3td>
          ????tr>
          ????<tr>
          ??????<td>2td>
          ??????<td>4td>
          ????tr>
          ??tbody>
          table>
          更改表格邊框
          表格的默認(rèn)邊框是1像素。要更改此默認(rèn)設(shè)置,我們可以將border參數(shù)設(shè)置為以像素為單位的值。
          以下代碼將邊框更改為3個(gè)像素值:
          import?pandas?as?pd

          df?=?pd.DataFrame({'A':?[1,?2],?'B':?[3,?4]})
          df.to_html('write_html.html',?border=3)
          現(xiàn)在,生成的文件將表的border屬性設(shè)置為“ 3”:
          <table?border="3"?class="dataframe">
          ??<thead>
          ????<tr?style="text-align:?right;">
          ??????<th>th>
          ??????<th>Ath>
          ??????<th>Bth>
          ????tr>
          ??thead>
          ??<tbody>
          ????<tr>
          ??????<th>0th>
          ??????<td>1td>
          ??????<td>3td>
          ????tr>
          ????<tr>
          ??????<th>1th>
          ??????<td>2td>
          ??????<td>4td>
          ????tr>
          ??tbody>
          table>
          對(duì)齊文字
          默認(rèn)情況下,表格的標(biāo)題文本是右對(duì)齊的。我們使用justify參數(shù)更改此對(duì)齊方式。例如,執(zhí)行justify =“ center”將添加style =“ text-align:center;”
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                    <th id="afajh"><progress id="afajh"></progress></th>
                    成人精品午夜无码免费 | 在线看的黄片网站 | 色也俺一区 | 大鸡巴操嫩逼视频 | 日本高清久久 |