gpt4 book ai didi

python - 使用 BeautifulSoup 抓取没有唯一标识符的元素

转载 作者:太空宇宙 更新时间:2023-11-04 02:14:36 25 4
gpt4 key购买 nike

我之前在 Python 中使用过少量网络抓取,但我被困在一个可能相当简单的问题上。

我想从 this page 上的表中提取费率.

我可以获得诸如单个元素或所有比率之类的东西(因为它们都列在“fccu__slash”类下,但我不知道如何以可用格式逐行获取结果。

这是我的代码的相关部分:

FCCU_url = "https://www.fccu.org/Rates/CD-Rates"
FCCU_resp = requests.get(FCCU_url, timeout=3)
FCCU_soup = BeautifulSoup(FCCU_resp.content, "html.parser")
for elem in FCCU_soup.find_all("td"):
try:
print(elem.contents[0])
except IndexError:
print(elem.contents)

这会输出我想要但不是可用格式的所有信息。

理想情况下,我希望能够只用我感兴趣的术语抓取 CD,并以这样的格式输出结果(我只关心费率而不关心 APY):

['3 Month', '0.65%', '0.75%']
['6 Month', '1.44%', '1.59%']
['2 Year', '2.37%', '2.62%']

这些不是我关心的具体内容,但一旦我了解如何去做,我想自己进行调整。

提前感谢您的帮助。

最佳答案

尝试以下代码以获得所需的输出:

FCCU_url = "https://www.fccu.org/Rates/CD-Rates"
FCCU_resp = requests.get(FCCU_url, timeout=3)
FCCU_soup = BeautifulSoup(FCCU_resp.content, "html.parser")
for elem in FCCU_soup.select("tbody tr"):
cells = [td for td in elem.findChildren('td')]
data = [cells[0].text, cells[2].span.text, cells[3].span.text]
print(data)

输出:

['3 Month', '0.65%', '0.75%']
['6 Month', '1.44%', '1.59%']
['1 Year', '2.13%', '2.37%']
['2 Year', '2.37%', '2.62%']
['3 Year', '2.27%', '2.52%']
['4 Year', '2.37%', '2.62%']
['5 Year', '2.96%', '3.20%']
['9 Month', '0.95%', '1.09%']
['19 Month', '1.98%', '2.08%']
['2 Year²', '2.27%', '2.52%']
['4 Year³', '2.32%', '2.57%']
['2 Year', '2.27%', 'N/A']

关于python - 使用 BeautifulSoup 抓取没有唯一标识符的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52935084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com