簡體   English   中英

除標簽外的BeautifulSoup HTML

[英]BeautifulSoup HTML except Tag

<tbody>
  <tr class="abc bg1">...</tr>
  <tr class="bg1">...</tr>
    <td> class="no">...</td>
    <td>sampletext</td>
    <td> class="title">...</td>
  <tr class="bg2">...</tr>

此示例代碼具有3個類'abc bg1','bg1','bg2'我只需要'bg1','bg2'標簽,因此我使用了soup.select('tbody > tr.bg1 > td')

這段代碼導致'abc bg1','bg1'標記為子代'td'。我如何獲得所需的結果? 對於'bg1',我只想提取文本,除了其他標簽,例如ex):sampletext <-only

from bs4 import BeautifulSoup

html_str = """<tbody>
  <tr class="abc bg1">...</tr>
  <tr class="bg1">...</tr>
    <td> class="no">...</td>
    <td>sampletext</td>
    <td> class="title">...</td>
  <tr class="bg2">...</tr><tobdy>"""

soup = BeautifulSoup(html_str)
bg1 = soup.findAll('tr', attrs= {'class':'bg1'})[1].text

如果您使用.findAll查找具有該類名稱的所有attrs。 它給你一個數組; 然后只需為所需的tr調用數組索引即可。

更新如果你想在bg1里面的元素; 呼叫另一個.find。 像這樣: sample_text = soup.findAll('td')[1].text #這給您“示例文本”。

這是一種識別所有具有“ bg1”或“ bg2”而不是“ abc”的標簽的方法:

from bs4 import BeautifulSoup

html_doc = '''<tbody>
    <tr class="abc bg1">...</tr>
    <tr class="bg1">...</tr>
        <td> class="no">...</td>
        <td>sampletext</td>
        <td> class="title">...</td>
    <tr class="bg2">...</tr>
</tbody>'''

soup = BeautifulSoup(html_doc, html.parser)


# We can look for all tags that are "tr" tags.
for tag in soup.find_all('tr'):

    # Each tag has attributes. We can reference the attrs dictionary
    #     using the attribute name as the key.
    if 'abc' in tag.attrs['class']:
        continue
    else:
        print(tag)

<tr class="bg1">...</tr>
<tr class="bg2">...</tr>

暫無
暫無

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

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