簡體   English   中英

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

[英]Scraping string from HTML with python3-beautifulsoup3

我正在嘗試使用 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>

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM