怎么刮Fidelity.com网站带着美丽的面纱

2024-10-03 23:27:46 发布

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

我试图从这一页中删除股票代码:

https://quotes.fidelity.com/mmnet/SymLookup.phtml?reqforlookup=REQUESTFORLOOKUP&productid=mmnet&isLoggedIn=mmnet&rows=50&for=stock&by=cusip&criteria=294100102&submit=Search.

在页面响应中,我看到:

<tr><td height="20" nowrap=""><font class="smallfont">ENZO BIOCHEM ORD SHS</font></td>
            <td align="center" width="20%"><font><a href="/webxpress/get_quote?QUOTE_TYPE=&amp;SID_VALUE_ID=ENZ">ENZ</a></font></td>
            <td><font>&nbsp;</font></td>
             <td><font></font></td></tr>    
        </tbody></table></td></tr>

我只需要打印ENZ。在

我该如何使用BeautifulSoup实现这一点?还有,有没有更简单的方法(看起来没有API,但我可能错了)?在

以下是我目前为止的代码:

^{pr2}$

Tags: httpscomtrquotestd股票代码fontproductid
1条回答
网友
1楼 · 发布于 2024-10-03 23:27:46

仅仅使用font a就可以作为css选择器。在

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://quotes.fidelity.com/mmnet/SymLookup.phtml?reqforlookup=REQUESTFORLOOKUP&productid=mmnet&isLoggedIn=mmnet&rows=50&for=stock&by=cusip&criteria=294100102&submit=Search')
soup = bs(r.content, 'lxml')
print(soup.select_one('font a').text)

另一种似乎相当健壮的方法是使用带有contains运算符的attribute = value选择器来瞄准a标记{}

^{pr2}$

在尝试访问.text之前,最好将匹配的元素设置为变量并测试None

例如

var = soup.select_one('[href*=SID_VALUE_ID]')
if var is None:
    print('Not found')
else:
    print(var.text)

相关问题 更多 >