BeautifulSoup4从预样式中提取和选择数据

2024-05-28 23:53:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从这个link中提取所有的short_name 我已经试过了,但是失败了。我得到的结果是'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塞族ADK和塞族ADK-C17。 但是,由于'None'值的原因,我无法从中选择任何数据

谢谢


Tags: namehttpsnone密码deflinkshortstr
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_nameSERBADK和SERBADK-C17,所以可以这样做

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

As请求以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_数据返回为列表,您可以使用索引值进行迭代

相关问题 更多 >

    热门问题