【问题标题】:Printing specific text from 2 spans on same line with beautifulsoup using python使用python从beautifulsoup在同一行打印2个跨度的特定文本
【发布时间】:2020-01-26 22:54:08
【问题描述】:

我正在通过基于视频游戏中的玩家提取多个统计数据来继续我的数据文件。我正在使用 BeautifulSoup 并且能够到达我想要的文本在字符串中的位置,但问题是存在两个跨度,因此当我使用 for 循环进行迭代时它会拉出多个字符串。

EXAMPLE TEXT FROM BEAUITFUL SOUP:
[<div class="stats-row"><span>0 kill rounds</span><span>6652</span></div>, 
<div class="stats-row"><span>1 kill rounds</span><span>4431</span></div>, 
<div class="stats-row"><span>2 kill rounds</span><span>2308</span></div>, 
<div class="stats-row"><span>3 kill rounds</span><span>861</span></div>, 
<div class="stats-row"><span>4 kill rounds</span><span>200</span></div>, 
<div class="stats-row"><span>5 kill rounds</span><span>49</span></div>]

我的 for 循环正在提取两个文本。

for stats in all_stats:
    print(stats.text)

0 kill rounds6652
1 kill rounds4431
2 kill rounds2308
3 kill rounds861
4 kill rounds200
5 kill rounds49

我只想要第二个跨度的具体数字:

<div class="stats-row"><span>TEXT I HATE!</span><span>TEXT I LOVE</span></div>

我尝试了 findChildren().. find_next().. find_next_sibling().. 我不断收到字符串错误.. 和 find_all() 错误的不同版本,我的意思是改用 find() 吗?我已经搜索了一个答案,但我找不到一个足够具体到我正在尝试做的事情的答案。

all_stats = soup.find('div',{'class':'columns'}).find('div',{'class':'stats-row'}).next_sibling('span')

TypeError: 'NavigableString' object is not callable

----------------------------------
"ResultSet object has no attribute '%s'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?" % key

我很快就要下班了,所以我回家后可以检查答案,所以如果有人在等待我的回复,我深表歉意。

我目前陷入困境的完整代码: https://www.codepile.net/pile/JP43EmrM

【问题讨论】:

    标签: python html beautifulsoup python-requests


    【解决方案1】:

    怎么样:

    for stats in all_stats:
        print(stats.find_all('span')[1].text)
    

    【讨论】:

    • 你知道如何将这些值添加到列表中吗?
    • 在进入循环之前创建一个列表,然后附加(而不是打印)到列表中。例如:some_list.append(stats.find_all('span')[1].text).
    猜你喜欢
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2017-07-03
    相关资源
    最近更新 更多