Skip to main content
 首页 » 编程设计

python之网页抓取,获取空列表

2024年10月24日15shangdawei

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

我正在尝试从 http://financials.morningstar.com/company-profile/c.action?t=AAPL 中抓取不同的信息. 我尝试了几种方法,有些似乎有效,有些则无效。 我对 Operation Details 下的 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()') 

我想不出最后一条路。看来我正确地遵循了路径,但我得到的是空列表。

请您参考如下方法:

问题是操作详细信息是通过额外的 GET 请求单独加载的。在您的代码中模拟它以维护网络垃圾 session :

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是由浏览器 插入的元素,用于定义表中的数据行。