输出显示两次BeautifulSoup Python

时间:2017-12-02 02:26:08

标签: python beautifulsoup request

当我尝试执行代码时,输​​出值显示两次。有没有办法只显示一次?

import requests
from bs4 import BeautifulSoup

def powr(url):
  source_code = requests.get(url)
  plain_text = source_code.text
  soup = BeautifulSoup(plain_text, 'html.parser')
  for text in soup.findAll('span', {'class': 'coin-page__price-number'}):
    head = text.string
    #print('Vertcoin =', head)
    print(head)

powr('https://coinranking.com/coin/power-ledger-powr')

输出:

0.695
0.695

2 个答案:

答案 0 :(得分:0)

使用find代替findAll解决问题。

当然你不再需要循环了。 : - )

答案 1 :(得分:0)

Easiest way to encounter this problem is to use return instead of print    at the end of your function.

def powr(url):
  source_code = requests.get(url)
  plain_text = source_code.text
  soup = BeautifulSoup(plain_text, 'html.parser')
  for text in soup.findAll('span', {'class': 'coin-page__price-number'}):
    head = text.string
  return head

powr('https://coinranking.com/coin/power-ledger-powr')