简体   繁体   中英

Soup.select method in python - how to choose only one score?

I want to display only first score of soup.select method, now i have this code:

score = soup.select('my_name a')
print(score)

urls = [tag['href'] for tag in score if 'href' in tag.attrs and "name" in tag['href']]
print(urls)

When bs finds only one score, it works very good. But how to choose only first score when i get more scores?

Now output is:

> [<a href="/name/adrian1021 "> Adrian </a>, <a href="/name/john.james"> John James </a>, <a href="/name/carol22 "> Carol Coat </a>]
> 
> ['/name/adrian1021 ', '/name/john.james ', '/name/carol22 ']

I want to extract only one score, for example output should be:

[/name/adrian1021 ']

Is that possible? I tried to work on this like on list but it does not work.

You are looking to use soup.select_one() which finds only the first element that matches a selector.

So your score variable should be:

score = soup.select_one('my_name a')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM