使用Python中的可点击内容刮取网站

时间:2015-03-11 04:04:34

标签: python python-2.7 web-scraping html-parsing

我想废弃以下网站的内容:

http://financials.morningstar.com/ratios/r.html?t=AMD

Key Ratios 下,我想点击"增长"按钮,然后在Python中废弃数据。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用requests + BeautifulSoup解决此问题。发送到http://financials.morningstar.com/financials/getKeyStatPart.html端点的异步GET请求需要模拟。 Growth表位于divid="tab-growth"

from bs4 import BeautifulSoup
import requests


url = 'http://financials.morningstar.com/ratios/r.html?t=AMD'
keystat_url = 'http://financials.morningstar.com/financials/getKeyStatPart.html'

with requests.Session() as session:
    session.headers = {'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'}

    # visit the target url
    session.get(url)

    params = {
        'callback': '',
        't': 'XNAS:AMD',
        'region': 'usa',
        'culture': 'en-US',
        'cur': '',
        'order': 'asc',
        '_': '1426047023943'
    }
    response = session.get(keystat_url, params=params)

    # get the HTML part from the JSON response
    soup = BeautifulSoup(response.json()['componentData'])

    # grab the data
    for row in soup.select('div#tab-growth table tr'):
        print row.text