【问题标题】:Scrape arraytodatatable with python用python刮掉arraytodatatable
【发布时间】:2015-08-15 19:10:34
【问题描述】:

我正在从this 页面,特别是“所有员工的统计表”中抓取数据。

当我尝试使用BeautifulSoup 或简单的正则表达式时,我无法拉表,大概是因为它是一个嵌套列表或因为换行符,尽管我真的不知道。

这里有一些示例代码:

url='http://www.forecasts.org/data/data/PAYEMS.htm'

def get( URL): #getting text from the web
    ses = requests.session()
    return ses.get(URL).text 

htmltext=get(url)

regex = 'Date(.+?)All' 
pattern = re.compile(regex)
nonFarm = re.findall(pattern,htmltext)

期望的输出:

[1939-01-01, 29923, 1939-02-01, 30101, ...]

【问题讨论】:

    标签: python regex web-scraping


    【解决方案1】:

    问题在于所需的数据在 javascript 代码中。

    我会使用正则表达式来解析 javascript 数组并使用literal_eval() 将其“加载”到 Python 列表中:

    from ast import literal_eval
    from pprint import pprint
    import re
    
    import requests
    
    
    url = 'http://www.forecasts.org/data/data/PAYEMS.htm'
    with requests.Session() as session:
        response = session.get(url)
    
        pattern = re.compile(r"data = google\.visualization\.arrayToDataTable\((.*?)\);", re.MULTILINE | re.DOTALL)
        data = pattern.search(response.content).group(1)
    
        data = literal_eval(data)
        pprint(data)
    

    打印:

    [['Date', 'All Employees: Total nonfarm'],
     ['1939-01-01', 29923],
     ['1939-02-01', 30101],
     ...
     ['2014-07-01', 138976],
     ['2014-08-01', 139118]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多