2017-09-07 27 views
1

我有这样的HTML如何使用python分割解析的html输出?

<tr class="BgWhite"> 
<td headers="th6" valign="top"> 
    0070648261<br/>QTY: 3 
</td> 
</tr> 

欲获得 “0070648261” 和 “3” 分别如在ID = 0070648261和数量= 3。我能够使用下面的代码

container1.find("td", {"headers": "th6"}).text.strip() 

产生这种输出

0070648261<br/>QTY: 3 

但我如何拆分和输出得到

ID = 0070648261 quantity = 3?

+0

只需拆分字符串...使用拆分功能 –

+0

您使用的是什么HTML解析库? –

回答

1

试试这个。

a="0070648261<br/>QTY: 3" 
a=a.split("<br/>") 
a="ID = "+a[0]+" quantity ="+a[1].split(':')[1] 

输出:

'ID = 0070648261 quantity = 3' 
1

为什么不这样做与正则表达式?

import re 
s = '<tr class="BgWhite"> <td headers="th6" valign="top">0070648261<br/>QTY: 3</td></tr>' 

res = re.findall(r'(\d+)<br/>QTY: (\d+)', s)[0] 
print('ID = {} quantity = {}'.format(res[0], res[1])) 
+1

这就是为什么https://stackoverflow.com/a/1732454/2308683 –

+0

_it有时适合解析一个有限的,已知的HTML集合._ - 从上面发送的帖子 – Val

+0

正确,但问题已解析为内部标签,所以当这个解决方案工作时,你也可以使用输出的字符串 –