我搜索来自凌乱的HTML文件的以下行:
<span id="fooPack1_xpl01_name11">150.00 FTL</span>
<span id="fooPack1_xpl02_name11">350.00 FTL</span>
<span id="fooPack1_xpl03_name11">250.00 FTL</span>
<span id="fooPack1_xpl04_name11">230.00 FTL</span>
我使用BeautifulSoup并重新搜索并找到字符串:
tags = soup.find_all('span', id=re.compile(r'[fooPack1_xpl04_name11]\d+'))
但显然,该字符串的共同部分是在开头和结尾,部分总是在中间变化。如何重构我的重新搜索模式,以便搜索“fooPack1_xpl”+(不同的字符串)+“_ name11”
感谢。
//编辑//
当我查询以下内容时:
<span id="FullView1_spl02_Stack_4">03/04/12</span>
<span id="FullView1_spl03_Stack_4">01/03/11</span>
<span id="FullView1_spl04_Stack_4">02/25/02</span>
<span id="FullView1_spl05_Stack_4">07/16/04</span>
<span id="FullView1_spl01_Stack32">999.00 SPL</span>
<span id="FullView1_spl02_Stack82">150.00 XPP</span>
<span id="FullView1_spl03_Stack82">350.00 XPP</span>
<span id="FullView1_spl04_Stack82">450.00 XPP</span>
<span id="FullView1_spl05_Stack82">550.00 XPP</span>
<span id="FullView1_spl06_Stack82">650.00 XPP</span>
<span id="FullView1_spl07_Stack22">888.00 SPL</span>
<span id="FullView1_spl202_stckFriendName">Red Car</span>
<span id="FullView1_spl203_stckFriendName">Green Car</span>
<span id="FullView1_spl204_stckFriendName">Blue Car</span>
使用:
foo=soup.findAll('span', id=re.compile(r'FullView1_spl\d+_stack82'))
我得到以下结果:
<span id="FullView1_spl204_stckFriendName">Blue Car</span>
<span id="FullView1_spl02_Stack82">150.00 XPP</span>
<span id="FullView1_spl03_Stack82">350.00 XPP</span>
<span id="FullView1_spl04_Stack82">450.00 XPP</span>
<span id="FullView1_spl05_Stack82">550.00 XPP</span>
<span id="FullView1_spl06_Stack82">650.00 XPP</span>
显然,我不需要检测顶部元素。所以这是唯一的问题。
答案 0 :(得分:0)
你快到了。您想要搜索fooPack1_xpl
后跟_name11
后跟的数字,那么如何:
re.compile(r'fooPack1_xpl\d+_name11')
请注意,我只是将\d+
放在您希望数字的位置,以及您正在搜索的文字字符串。