使用python选择文本的特定部分

2024-04-19 11:18:18 发布

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

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import numpy as np
import pandas as pd


my_url = 'https://sg.finance.yahoo.com/quote/S63.SI/history?p=S63.SI'


uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# html parsing
page_soup = soup(page_html, "html.parser")

item = container.findAll("td", {"class":"D(ib) Fz(18px)"})
print(item.text)

输出

Singapore Technologies Engineering Ltd (S63.SI)

我只需要得到S63.SI他们是否仍要过滤我的输出,这样就不会给出上面看到的其余输出


Tags: fromimporturlrequestmyhtmlaspage
3条回答

这是一种不使用正则表达式的方法:

text = "Singapore Technologies Engineering Ltd (S63.SI)"

ib = text[text.find("(")+1:text.find(")")]

print(ib)

输出:

S63.SI

您可以使用正则表达式来捕获数据中的值

import re
text = "Singapore Technologies Engineering Ltd(S63.SI)"
result = re.findall(r'\(([\w\d\.]+)\)', text)
print(result)

输出:

['S63.SI']

您应该使用类似于r的正则表达式。“((.eem>)$”将匹配字符串,并将括号之间的内容放入group1。有关详细信息,请参见https://regex101.com/

import re

regex = r".*\((.*)\)$"

test_str = "Singapore Technologies Engineering Ltd (S63.SI)"

matches = re.finditer(regex, test_str, re.MULTILINE)

相关问题 更多 >