【问题标题】:BeautifulSoup4 extract and select data from pre styleBeautifulSoup4 从 pre 样式中提取和选择数据
【发布时间】:2021-09-21 10:15:28
【问题描述】:

我想从这个link 中提取所有short_name 我已经尝试过关注这个answer,但它失败了。我得到的结果是'None'

这是我的代码:

def checkStockIdExistOrNot(stockIdNumberOrName):

    BursaStockSearchIdURL = 'https://www.bursamalaysia.com/api/v1/search/stock_list?keyword=' + str(stockIdNumberOrName) + '&lang=EN&limit=99'
    BursaStockSearchIdRequest = requests.get(str(BursaStockSearchIdURL), headers=header)
    BursaStockSearchIdParser = BeautifulSoup(BursaStockSearchIdRequest.content, 'html.parser')
    BursaSelection = BursaStockSearchIdParser.find('pre')
    print(BursaSelection)

checkStockIdExistOrNot('SERBADK')

我的意图是只获得short_name SERBADK 和 SERBADK-C17。 但是,由于 'None' 的值,我无法从中选择/挑选任何单个数据。

谢谢!

【问题讨论】:

    标签: python web-scraping beautifulsoup tags


    【解决方案1】:

    由于请求以json 格式返回数据,因此您可以直接使用.json 方法从中提取数据!

    import requests
    res=requests.get("https://www.bursamalaysia.com/api/v1/search/stock_list?keyword=SERBADK&lang=EN&limit=99")
    main_data=res.json()['data']
    for i in range(len(main_data)):
        print(main_data[i]['short_name'])
    

    输出:

    SERBADK
    SERBADK-C16
    SERBADK-C17
    SERBADK-C20
    SERBADK-C21
    SERBADK-C22
    SERBADK-C23
    SERBADK-C24
    SERBADK-C25
    SERBADK-C26
    SERBADK-WA
    

    为了找到你可以使用的第一个元素

    main_data[0]['short_name']

    main_data 作为列表返回,您可以使用索引值进行迭代

    【讨论】:

    • 我怎样才能只打印最上面的一个 - SERBADK?
    • 更新了我的答案
    【解决方案2】:

    由于数据为 JSON 格式,您无需为此使用BeautifulSoup 并从pre 中选择数据。

    只需使用 (response.json()) 将 response 转换为 JSON 并提取您需要的数据。

    此代码将打印所有short_names

    import requests
    
    def checkStockIdExistOrNot(stockIdNumberOrName):
        url = 'https://www.bursamalaysia.com/api/v1/search/stock_list?keyword=' + str(stockIdNumberOrName) + '&lang=EN&limit=99'
        response = requests.get(url)
        info = response.json()
    
        for i in info['data']:
            print(i['short_name'])
    
    checkStockIdExistOrNot('SERBADK')
    
    
    SERBADK
    SERBADK-C16
    SERBADK-C17
    SERBADK-C20
    SERBADK-C21
    SERBADK-C22
    SERBADK-C23
    SERBADK-C24
    SERBADK-C25
    SERBADK-C26
    SERBADK-WA
    

    由于您打算只获得short_name SERBADK 和 SERBADK-C17,您可以这样做

    for i in info['data']:
            if i['short_name'] in ['SERBADK', 'SERBADK-C17']:
                print(i['short_name'])
    
    SERBADK
    SERBADK-C17
    

    【讨论】:

    • 嘿,谢谢!我也可以通过 listName = [] for i in info['data']: listAll = (i['short_name']) listName.append(listAll) print(listName[0]) 根据您的代码获得结果。非常感谢他们!
    猜你喜欢
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2014-08-09
    • 2018-09-17
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多