从图上网络抓取数据

时间:2019-08-28 15:10:59

标签: python web-scraping

我正在处理来自opensecrets.org的游说数据,特别是行业数据。我想对90年代以来每个行业的游说支出进行时间排序。

我想自动对数据进行Web剪贴。提示数据的格式如下:

https://www.opensecrets.org/lobby/indusclient.php?id=H04&year=2019

它们很容易嵌入循环中,问题是我需要的数据在网页中不是简单的格式。它在条形图中,当我检查该图时,我不知道如何获取数据,因为它不在html代码中。当数据位于html代码中时,我熟悉python中的网络抓取,但是在这种情况下,我不确定如何继续。

1 个答案:

答案 0 :(得分:0)

如果有API,那么最好的选择就是如上所述。但是只要您获得正确的url / query参数,就可以对数据进行解析:

我已经设法通过链接对它进行遍历,以便您获取每个表。我将其存储在字典中,键为公司名称,值为表/数据。您可以根据需要进行更改。也许只是存储为json,或将每个保存为csv。

代码:

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://www.opensecrets.org/lobby/indusclient.php?id=H04&year=2019'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'}

data = requests.get(url, headers=headers)
soup = BeautifulSoup(data.text, 'html.parser')


links = soup.find_all('a', href=True)

root_url = 'https://www.opensecrets.org/lobby/include/IMG_client_year_comp.php?'
links_dict = {}

for each in links:
    if 'clientsum.php?' in each['href']:
        w=1
        firms = each.text
        link = root_url + each['href'].split('?')[-1].split('&')[0].strip() + '&type=c'
        links_dict[firms] = link


all_tables = {}
n=1
tot = len(links_dict)
for firms, link in links_dict.items():

    print ('%s of %s  ---- %s' %(n, tot, firms))
    data = requests.get(link)
    soup = BeautifulSoup(data.text, 'html.parser')

    results = pd.DataFrame()
    graph = soup.find_all('set')

    for each in graph:
        year = each['label']
        total = each['value']

        temp_df = pd.DataFrame([[year, total]], columns=['year','$mil'])
        results = results.append(temp_df,sort=True).reset_index(drop=True)

    all_tables[firms] = results
    n+=1

*输出:**

因为有347个表格,所以不会打印,只是这样您就可以看到结构:

enter image description here