如何获得带有注释的类的非注释内容?

2024-10-04 01:36:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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",如下所示:

<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>]

Tags: textdiv网页botcolumnallfindreact
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)

enter image description here

如果使用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

相关问题 更多 >