gpt4 book ai didi

python - BeautifulSoup 为 .find 和 .find_all 提供不同的结果

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

我正在尝试完成实用数据分析书中的练习,目标是从网站上抓取黄金价格。原始代码不起作用,我已将其追溯到我认为是从 original script 时起对网站进行的重新设计。 .

为了让练习继续进行,我一直在努力修改脚本:

from bs4 import BeautifulSoup
import requests
import re
from time import sleep
from datetime import datetime

def getGoldPrice():
url = "http://www.gold.org"
req = requests.get(url)
soup = BeautifulSoup(req.text, "lxml")
price = soup.find_all("dd", class_="value")[1]
return price

with open("goldPrice.out","w") as f:
for x in range(0,3):
sNow = datetime.now().strftime("%I:%M:%S%p")
f.write("{0}, {1} \n ".format(sNow, getGoldPrice()))
sleep(59)

这对初始部分有效,直到我意识到它并不是每分钟都更新事件标签(最初的目标)。做了一点之后more research我发现我可以用

soup.find('script', type="text/javascript").text

代替 .find_all() 用法并在脚本上运行正则表达式。

除原始帖子正则表达式外,这非常有效,因此我正在研究使用什么来获取“询问”组的价格。当我返回在文件上调用这个更新后的正则表达式时,我的表达式不再提供相同的基本结果。

目前如果我做一个

soup.find_all('script', type="text/javascript")

我得到了一组与

不同的结果
soup.find('script', type="text/javascript").text

不幸的是,我似乎无法像 soup.find 命令那样将 soup.find_all 结果放入 .text 命令中。是否缺少此命令的一部分,导致我得到如此不同的结果?

感谢您的帮助!

编辑:借助答案中的帮助,我最终使用以下几行代码替换了 price 组件以获得我正在寻找的内容!

js_text = soup.find_all('script', type="text/javascript")[10]
js_text = js_text.string
regex = re.compile('"ask":{"css":"minus","price":"(.*)","performance":-1}},"G')
price = re.findall(regex, js_text)

无可否认,我的正则表达式非常适合我的问题。

最佳答案

for a in soup.find_all('script', type="text/javascript"):
print(a.text)

find_all() 将返回如下标签列表:

[tag1, tag2, tag3]

find() 只会返回第一个标签:

tag1

如果要获取标签列表中的所有标签,使用for循环迭代即可。

关于python - BeautifulSoup 为 .find 和 .find_all 提供不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41886437/

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