网络抓取,获取空列表

时间:2015-10-14 18:28:36

标签: python web-scraping

我很难用我的网络抓取代码找出正确的路径。

我正试图从http://financials.morningstar.com/company-profile/c.action?t=AAPL抓取不同的信息。 我尝试了几种方法,有些似乎有效,有些则没有。 我对“操作细节”下的CIK感兴趣

page = requests.get('http://financials.morningstar.com/company-profile/c.action?t=AAPL')
tree=html.fromstring(page.text)


#desc = tree.xpath('//div[@class="r_title"]/span[@class="gry"]/text()')  #works

#desc = tree.xpath('//div[@class="wrapper"]//div[@class="headerwrap"]//div[@class="h_Logo"]//div[@class="h_Logo_row1"]//div[@class="greeter"]/text()')    #works

#desc = tree.xpath('//div[@id="OAS_TopLeft"]//script[@type="text/javascript"]/text()')   #works

desc = tree.xpath('//div[@class="col2"]//div[@id="OperationDetails"]//table[@class="r_table1 r_txt2"]//tbody//tr//th[@class="row_lbl"]/text()')

我无法想出最后的路径。看起来我正确地遵循了路径,但我得到了空列表。

1 个答案:

答案 0 :(得分:2)

问题是操作细节是单独加载的,还有一个额外的GET请求。在代码中模拟它,维护web-scrapin会话:

import requests
from lxml import html


with requests.Session() as session:
    page = session.get('http://financials.morningstar.com/company-profile/c.action?t=AAPL')
    tree = html.fromstring(page.text)

    # get the operational details
    response = session.get("http://financials.morningstar.com/company-profile/component.action", params={
        "component": "OperationDetails",
        "t": "XNAS:AAPL",
        "region": "usa",
        "culture": "en-US",
        "cur": "",
        "_": "1444848178406"
    })

    tree_details = html.fromstring(response.content)
    print tree_details.xpath('.//th[@class="row_lbl"]//text()')

旧答案:

只是你应该从表达式中删除tbody

//div[@class="col2"]//div[@id="OperationDetails"]//table[@class="r_table1 r_txt2"]//tr//th[@class="row_lbl"]/text()

tbody浏览器插入的元素,用于定义表中的数据行。