我想只返回这3个玩家的名字(在网址中)..当前代码返回他们的名字,他们的团队和他们的篮球协会。我可以在代码中指定只返回名称吗?
来自here的数据抓取:
import requests
from bs4 import BeautifulSoup
def bball_spider(str):
source_code = requests.get(str)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
# Players
for elements in soup.find('table' , {'id' : 'stats'}).findAll('a'):
names = elements.string
print(names)
str = input("Enter the Query Result URL ")
bball_spider(str)
答案 0 :(得分:1)
你几乎就在那里,但首先让我提一下,因为你似乎不熟悉Python:你不应该命名变量str
,因为它会影响内置的 str < / em> class,这是我在下面显示的代码中修改的内容。重要的修改是我将您的.findAll('a')
更改为.findAll('td',{'class':'left active'})
,检查了我们可以看到玩家的所有名称都在<td>
标记中且类left active
的元素。我还将迭代var更改为element
而不是复数,因此从语义上讲它更有意义。另外请注意你发布的代码没有被正确识别,但我认为这只是你在这里粘贴时的格式问题。
import requests
from bs4 import BeautifulSoup
def bball_spider(url):
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
# Players
for element in soup.find('table',{'id' : 'stats'}).findAll('td',{'class':'left active'}):
names = element.string
print(names)
url = '''https://www.basketball-reference.com/play-index/psl_finder.cgi?request=1&match=single&type=totals&per_minute_base=36&per_poss_base=100&season_start=1&season_end=-1&lg_id=NBA&age_min=0&age_max=99&is_playoffs=N&height_min=0&height_max=99&year_min=2017&year_max=2017&birth_country_is=Y&as_comp=gt&as_val=0&pos_is_g=Y&pos_is_gf=Y&pos_is_f=Y&pos_is_fg=Y&pos_is_fc=Y&pos_is_c=Y&pos_is_cf=Y&c1stat=fg3_pct&c1comp=gt&c1val=40&c2stat=fg3a&c2comp=gt&c2val=164&c3stat=dbpm&c3comp=gt&c3val=0&order_by=ws'''
bball_spider(url)
这将打印:
Chris Paul
Otto Porter
Joe Ingles