试图从类元素中获取HTML的一小部分

2024-04-25 05:53:59 发布

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

我断断续续地使用BeautifulSoup已经有几年了,但我仍然时不时地被绊倒。我把这些代码放在一起

from bs4 import BeautifulSoup
from bs4.dammit import EncodingDetector
import requests

resp = requests.get("https://finance.yahoo.com/gainers")
http_encoding = resp.encoding if 'charset' in resp.headers.get('content-type', '').lower() else None
html_encoding = EncodingDetector.find_declared_encoding(resp.content, is_html=True)
encoding = html_encoding or http_encoding
soup = BeautifulSoup(resp.content, from_encoding=encoding)
myclass = soup.findAll("a", {"class": "Fw(600) C($linkColor)"})
myclass

这给了我这个

[<a class="Fw(600) C($linkColor)" data-reactid="79" href="/quote/TSNP?p=TSNP" title="Tesoro Enterprises, Inc.">TSNP</a>,
 <a class="Fw(600) C($linkColor)" data-reactid="105" href="/quote/FDVRF?p=FDVRF" title="Facedrive Inc.">FDVRF</a>,
 <a class="Fw(600) C($linkColor)" data-reactid="131" href="/quote/SKLZ?p=SKLZ" title="Skillz Inc.">SKLZ</a>,
 <a class="Fw(600) C($linkColor)" data-reactid="157" href="/quote/GOOS?p=GOOS" title="Canada Goose Holdings Inc.">GOOS</a>,
 <a class="Fw(600) C($linkColor)" data-reactid="183" href="/quote/WMS?p=WMS" title="Advanced Drainage Systems, Inc.">WMS</a>, etc., etc.

我真正想要的是股票符号:TSNP、FDVRF、SKLZ、GOOS、WMS等

如何修改此代码以仅获取股票符号?我试着使用正则表达式,但我从来都不是很熟练

谢谢大家


1条回答
网友
1楼 · 发布于 2024-04-25 05:53:59

您可以使用从.findAll()方法返回的元素的.text属性:

for e in soup.findAll("a", {"class": "Fw(600) C($linkColor)"}):
    print(e.text)

输出:

TSNP
FDVRF
SKLZ
GOOS
WMS
APPS
...

如果您希望将它们列在列表中,简单的列表理解即可:

gainers = soup.findAll("a", {"class": "Fw(600) C($linkColor)"})
tickers = [e.text for e in gainers]

输出:

['TSNP', 'FDVRF', 'SKLZ', 'GOOS', 'WMS', 'APPS', 'TIGR', ...]

相关问题 更多 >