【问题标题】:BeautifulSoup is providing different results for .find and .find_allBeautifulSoup 为 .find 和 .find_all 提供了不同的结果
【发布时间】:2017-06-12 16:33:57
【问题描述】:

我正在尝试完成一本实用数据分析书中的练习,其目标是从网站上获取黄金价格。原始代码不起作用,我已将其追溯到我认为是从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 之后,我发现我可以通过 a

深入研究一下
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_all 结果转换为 .text 命令,就像我可以为 soup.find 命令所做的那样。我是否缺少此命令的一部分以得到如此不同的结果?

感谢您的帮助!

编辑:使用来自答案的帮助,我最终使用以下几行来替换 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)

诚然,我的正则表达式非常适合我的问题。

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:
    for a in soup.find_all('script', type="text/javascript"):
        print(a.text)
    

    find_all() 将返回一个标签列表,如:

    [tag1, tag2, tag3]
    

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

    tag1
    

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

    【讨论】:

    • 感谢您的帮助! for 循环没有得到我正在寻找的结果,但由于它是标签列表与单个标签的解释,我能够获得我正在寻找的特定部分的正确索引并能够获得正则表达式来缩小我需要的范围!
    猜你喜欢
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 2017-07-17
    相关资源
    最近更新 更多