亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 python3-beautifulsoup3 從 HTML 中抓取字符串

使用 python3-beautifulsoup3 從 HTML 中抓取字符串

阿晨1998 2023-03-16 17:02:52
我正在嘗試使用 beautifulsoup 從表行中獲取字符串。我想要獲取的字符串是第二行和第三行的“SANDAL”和“SHORTS”。我知道這可以用正則表達式或字符串函數來解決,但我想學習 beautifulsoup 并盡可能多地使用 beautifulsoup。截取的 python 代碼    soup=beautifulsoup(page,'html.parser')    table=soup.find('table')    row=table.find_next('tr')    row=row.find_next('tr')HTML    <html>    <body>    <div id="body">    <div class="data">        <table id="products">        <tr><td>PRODUCT<td class="ole1">ID<td class="c1">TYPE<td class="ole1">WHEN<td class="ole4">ID<td class="ole4">ID</td></tr>    <tr><td>SANDAL<td class="ole1">77313<td class="ole1">wear<td class="ole1">new<td class="ole4">id<td class="ole4">878717</td></tr>    <tr><td>SHORTS<td class="ole1">77314<td class="ole1">wear<td class="ole1">new<td class="ole4">id<td class="ole4">878718</td></tr>        </table>        </div>    </div>    </body>    </html>
查看完整描述

1 回答

?
冉冉說

TA貢獻1877條經驗 獲得超1個贊

要從表格的第一列(無標題)獲取文本,您可以使用此腳本:


from bs4 import BeautifulSoup



txt = '''

    <html>

    <body>

    <div id="body">

    <div class="data">


    <table id="products">


    <tr><td>PRODUCT<td class="ole1">ID<td class="c1">TYPE<td class="ole1">WHEN<td class="ole4">ID<td class="ole4">ID</td></tr>

    <tr><td>SANDAL<td class="ole1">77313<td class="ole1">wear<td class="ole1">new<td class="ole4">id<td class="ole4">878717</td></tr>

    <tr><td>SHORTS<td class="ole1">77314<td class="ole1">wear<td class="ole1">new<td class="ole4">id<td class="ole4">878718</td></tr>


    </table>


    </div>

    </div>

    </body>

    </html>'''


soup = BeautifulSoup(txt, 'lxml')  # <-- lxml is important here (to parse the HTML code correctly)


for tr in soup.find('table', id='products').find_all('tr')[1:]:  # <-- [1:] because we want to skip the header

    print(tr.td.text)                                            # <-- print contents of first <td> tag

印刷:


SANDAL

SHORTS


查看完整回答
反對 回復 2023-03-16
  • 1 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號