【问题标题】:How to scrape values from a graph on a website如何从网站上的图表中抓取值
【发布时间】:2021-10-25 00:37:54
【问题描述】:

我正在尝试从三个图表中抓取数据:

网站:https://www.worldometers.info/coronavirus/country/us/ 图 1:美国冠状病毒病例总数 图 2:美国的活跃病例 图 3:美国冠状病毒总死亡人数

到目前为止,我已经从 stackoverflow 和其他位置编写/提取了代码:

from selenium import webdriver
from bs4 import BeautifulSoup as bs
import time
import json
import re

# set options to be headless, ..
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

# open it, go to a website, and get results
driver = webdriver.Chrome('chromedriver',options=options)
driver.get("https://www.worldometers.info/coronavirus/country/us/")

html = driver.page_source

soup = bs(html, "html.parser")

# get all scripts tags and select the one of interest
balises_script = soup.find_all("script")
target_balise = [str(el) for el in balises_script if "xAxis" in str(el)][0]

# use regex to extract dict like string 
m = re.findall(r"xAxis = (.+)\;", target_balise)[0]

# Rest of the code

# dict like string to dict
#data = json.loads(m)

# explore data to see where data of interest is
#sub_data_of_interest = data['overview']['EngagementsSimilarweb']['WeeklyTrafficNumbers']

#for items in sub_data_of_interest.items():
#    print(items)

#driver.close()

我的问题是: 我应该定位和选择的脚本标签是什么? 如何提取日期和对应的数字?

提前致谢。

【问题讨论】:

    标签: python selenium beautifulsoup


    【解决方案1】:

    图表的数据位于源 HTML 中的 <script> 标记中。

    您可以使用bs4 找到那些并使用regex 魔术提取日期和值。

    方法如下:

    import json
    import re
    import requests
    from bs4 import BeautifulSoup
    
    
    url = "https://www.worldometers.info/coronavirus/country/us/"
    html = requests.get(url).text
    
    scripts = [
        script.string for script in
        BeautifulSoup(html, "lxml").find_all("script", {"type": "text/javascript"})
        if script.string is not None
    ]
    
    graph_titles = [
        "Active Cases",
        "Total Coronavirus Cases",
        "Total Coronavirus Deaths",
    ]
    
    output = {}
    
    for script in scripts:
        scrip_body = script.string
        for title in graph_titles:
            if title in scrip_body:
                c = re.search(r"categories: \[(.*)\]", script.string).group(1)
                d = re.search(r"data: \[(.*)\]\s+}", script.string).group(1).split(",")
                output[title] = {
                    "dates": re.findall(r"[A-Za-z]{3} \d{1,2}, \d{4}", c),
                    "series": d,
                }
            else:
                continue
    
    with open("your_graphs.json", "w") as json_file:
        json.dump(output, json_file, indent=4, sort_keys=True)
    

    这应该会给你一个JSON 文件,看起来像这样:

    然后您可以使用它来绘制数据(或做任何您想做的事情)。

    【讨论】:

    • 非常感谢。你能帮我把数据放在 csv 文件而不是 json 文件中吗?
    猜你喜欢
    • 2016-09-08
    • 2017-02-13
    • 2017-11-26
    • 1970-01-01
    • 2017-10-16
    • 2013-05-21
    • 2022-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多