如何解决无法将列表分组以正确打印,也无法获取功能?
SymbolTime (NY)Message FAMI08/14/20,19:59:52Block trade. At the bid. (NYSEArca) KTOV08/14/20,19:59:31Block trade. At the ask.
上面的信息就是我要解析的。
我遇到两个问题。我无法将整行信息作为一个组打印,而是单独打印。
第二个;我无法打印href元素。该程序将打印第一个href,然后代码中断。我这是我的代码;
def function_time():
global url,scan_type,name
response = session.get(url)
response = session.get
soup = bs(response.text,'html.parser')
data = soup.findAll()
page = requests.get(url)
doc = lh.fromstring(page.content)
#Parse data that are stored between <tr>..</tr> of HTML
tr_elements = doc.xpath('//tr')
tr_elements = doc.xpath('//tr')
#Create empty list
col=[]
i=0
for t in tr_elements[1]:
name=t.text_content()
#link = t.find('a').get('href')
#print(link) #finds first then breaks
print (Fore.GREEN+name)
col.append((name,[]))
time.sleep(1)
function_time()
当前打印为
FAMI
08/14/2020
Block Trade
我想将其打印为;
FAMI 08/14/2020 Block Trade
,并修复href函数(尽管打印了第一个,但由于没有get函数错误而当前结束。)
我仍在学习技巧,在研究时无法弄清楚如何表达我的问题。预先感谢!
解决方法
您可以执行以下操作:
x = []
for t in tr_elements[1]:
name=t.text_content()
#link = t.find('a').get('href')
#print(link) #finds first then breaks
x.append(name)
col.append((name,[]))
time.sleep(1)
print(' '.join(x))
简要介绍:
- .join将列表中的所有项目连接成一个字符串,并由您在字符串之前定义的任何内容(在本例中为'')连接起来。
- 我们将
name
附加到列表中,而不是立即将其打印出来。
使用正则表达式如何?
假设您的数据与示例的结构相同。
import re
strs = '''
SymbolTime (NY)Message
<a href="/StockInfo/?symbol=FAMI">FAMI</a>08/14/20,19:59:52Block trade. At the bid. (NYSEArca)
<a href="/StockInfo/?symbol=KTOV">KTOV</a>08/14/20,19:59:31Block trade. At the ask.
'''
patterns = [
re.compile(r'(?<=>)\w+(?=</a>)'),re.compile(r'\d+/\d+/\d+'),re.compile(r'(?<=:\d\d)[\w\s]+(?=.)')
]
# First pattern: match ticker
# Second pattern: match date
# Third pattern: match trade type
for s in strs.split('\n'): # Split your document into lines
if 'href' in s: # If 'href' in this line,parse this line
results = []
for pattern in patterns:
results.append(pattern.findall(s)[0]) # Find the three elements one by one
result_str = ' '.join(results) # Combine them into one string
print(result_str)
结果:
'FAMI 08/14/20 Block trade'
'KTOV 08/14/20 Block trade'
对于第一个问题,您可以通过两种方式解决:
print('FAMI',end=' ')
print('08/14/20',end=' ')
print('Block trade',end=' ')
或
s = ' '.join(['FAMI','08/14/20','Block trade')
print(s)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。