簡體   English   中英

BeautifulSoup:如何獲取帶有注釋的課程的非注釋內容?

[英]BeautifulSoup: How to get the non-comment-content of a class with comments?

我正在嘗試使用BeautifulSoup從網頁獲取數據。 它適用於大多數數據,但一個類的工作原理似乎有所不同,我不知道該怎么辦。 評論可能會影響soup.find_all嗎?

因此,我有一個網頁,其中包含多個具有相同名稱的類,並且正在使用soup.find_all查找內容。 盡管這適用於class "points column" ,但始終如下所示:

<div class="points column">Punkte</div>
<div class="points column">45.677</div>
<div class="points column">43.445</div>
...

對於class "teamValue column"class "teamValue column" ,如下所示:

<div class="teamValue column">Teamwert</div>
<div class="teamValue column">
<!-- react-text: 690 -->
554,4
<!-- /react-text -->
<!-- react-text: 691 -->
 €
<!-- /react-text -->
</div>
<div class="teamValue column">
<!-- react-text: 705 -->
449,7
<!-- /react-text -->
<!-- react-text: 706 -->
 €
<!-- /react-text -->
</div>
...

這是我的代碼:

def getplayerdata(self):
    bot = self.bot
    soup = BeautifulSoup(bot.page_source, 'html.parser')

    playervalue = soup.find_all("div",class_="teamValue column",text=True)
    playerpoints = soup.find_all("div",class_="points column",text=True)

    print(playervalue)
    print(playerpoints)

playerpoints的輸出按預期工作,我獲得了所有數據,並且只能使用.string命令提取文本。

但是對於playervalue我在列表中僅得到一個元素,即:

[<div class="teamValue column">Teamwert</div>]

如果我用我能得到這個文本find_all()text=True.get_text().text代替.string

from bs4 import BeautifulSoup as BS

text = '''<div class="teamValue column">Teamwert</div>
<div class="teamValue column">
<!-- react-text: 690 -->
554,4
<!-- /react-text -->
<!-- react-text: 691 -->
 €
<!-- /react-text -->
</div>
<div class="teamValue column">
<!-- react-text: 705 -->
449,7
<!-- /react-text -->
<!-- react-text: 706 -->
 €
<!-- /react-text -->
</div>'''

soup = BS(text, 'html.parser')

all_items = soup.find_all('div',class_="teamValue column") #text=True)


for item in all_items:
    print('1>', item.text)

for item in all_items:
    print('2>', item.get_text(strip=True, separator=' '))

for item in all_items:
    print('3>', item.string)

結果:

1> Teamwert
1> 

554,4


 €


1> 

449,7


 €


2> Teamwert
2> 554,4 €
2> 449,7 €
3> Teamwert
3> None
3> None

只需更改text= False :)

playervalue = soup.find_all("div",class_="teamValue column",text=False)
print(len(playervalue))

出:

3

您可以使用soup.select和re.sub擺脫新行

from bs4 import BeautifulSoup
import re

html = '''
<div class="teamValue column">Teamwert</div>
<div class="teamValue column">
<!-- react-text: 690 -->
554,4
<!-- /react-text -->
<!-- react-text: 691 -->
 €
<!-- /react-text -->
</div>
<div class="teamValue column">
<!-- react-text: 705 -->
449,7
<!-- /react-text -->
<!-- react-text: 706 -->
 €
<!-- /react-text -->
</div>'''

soup = bs(html, 'lxml')
team_values = [re.sub('\n+', '',item.text) for item in soup.select('.teamValue.column')]
print(team_values)

在此處輸入圖片說明

暫無
暫無

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

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