【问题标题】:BeautifulSoup .get_text() element returns no resultsBeautifulSoup .get_text() 元素不返回任何结果
【发布时间】:2020-07-25 19:57:34
【问题描述】:

由于某种原因,下面的代码在运行相同 python 版本 3.8.1 64 位的不同笔记本电脑上没有返回任何结果,我不知道为什么...我尝试了 3 台不同的笔记本电脑,图表仅在一台上打印结果其中。

有没有人知道可能有什么不同,或者完全相同的代码在一台机器上运行而在另一台机器上运行的原因是什么?

import requests
from bs4 import BeautifulSoup

def check_facebook():

URL = 'https://downdetector.com/status/facebook/'

browser = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'}

page = requests.get(URL, headers=browser)
soup = BeautifulSoup(page.content, 'html.parser')


chart = soup.find("div",{"class":"popover-container justify-content-center p-relative"}).script.get_text()


print("Facebook chart:", chart)

check_facebook()

【问题讨论】:

    标签: python-3.x beautifulsoup


    【解决方案1】:

    使用.string属性代替.get_text()获取<script>标签的内容:

    import re
    import requests
    from bs4 import BeautifulSoup
    
    def check_facebook():
        URL = 'https://downdetector.com/status/facebook/'
        browser = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36'}
        page = requests.get(URL, headers=browser)
        soup = BeautifulSoup(page.content, 'html.parser')
        chart = soup.find("div",{"class":"popover-container justify-content-center p-relative"}).script.string
        print('Status:', re.search(r"status: '(.*?)'", chart).group(1))
        print('Baseline:', re.search(r"baseline: (\d+)", chart).group(1))
        print('Company:', re.search(r"company: '(.*?)'", chart).group(1))
        print('Max:', re.search(r"max: (\d+)", chart).group(1))
        for x, y in re.findall(r"x: '(.*?)', y: (\d+)", chart):
            print(x, y)
    
    check_facebook()
    

    打印:

    Status: success
    Baseline: 28
    Company: Facebook
    Max: 37
    2020-07-24T18:29:28.479584-04:00 33
    2020-07-24T18:44:28.479584-04:00 27
    2020-07-24T18:59:28.479584-04:00 31
    
    ...and so on.
    

    【讨论】:

    • 谢谢安德烈,遗憾的是,这个解决方案对我不起作用,因为我需要从图表中查看其他信息,例如“状态”、“基线”、“最大值:”。我试图让 get_text() 在其他机器上工作,但由于某种原因它没有返回任何东西。当 .get_text() 工作时,我使用以下内容收集例如 'max:' number: chart = soup.find("div",{"class":"popover-container justify-content-center p-relative"} ).script.get_text() max_val = chart.split("max: ")[1].split(",")[0] print("Facebook 过去 24 小时内的最大报告数:", max_val)
    • @Shaggy 我更新了我的答案。只需执行print(chart) 即可打印<script> 标签的所有内容。
    猜你喜欢
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 2021-11-21
    • 2015-05-18
    • 2020-10-13
    • 1970-01-01
    • 2020-04-23
    相关资源
    最近更新 更多