我可以通過beautifulsoup在以下HTML標簽中獲取數字嗎?<tr align="center" height="15" id="tr_1599656" bgcolor="#ffffff" index="0"></tr><tr align="center" height="15" id="tr_1599657" bgcolor="#ffffff" index="1"></tr><tr align="center" height="15" id="tr_1599644" bgcolor="#ffffff" index="2"></tr>我嘗試過的Python代碼from bs4 import BeautifulSoupimport rehtml_code = """"<tr align="center" height="15" id="tr_1599656" bgcolor="#ffffff" index="0"></tr><tr align="center" height="15" id="tr_1599657" bgcolor="#ffffff" index="1"></tr><tr align="center" height="15" id="tr_1599644" bgcolor="#ffffff" index="2"></tr>"""soup = BeautifulSoup(html_code,'html.parser')rows = soup.findAll("tr", {"id" : re.compile('tr_*\d')})print rows預期產量159965615996571599644
2 回答

HUH函數
TA貢獻1836條經驗 獲得超4個贊
soup=BeautifulSoup('<tr align="center" height="15" id="tr_1599656" bgcolor="#ffffff" index="0"></tr><tr align="center" height="15" id="tr_1599657" bgcolor="#ffffff" index="1"></tr><tr align="center" height="15" id="tr_1599644" bgcolor="#ffffff" index="2"></tr>')
lines=soup.find_all('tr')
for line in lines:print(re.findall('\d+',line['id'])[0])
請下次自行嘗試一次。

嚕嚕噠
TA貢獻1784條經驗 獲得超7個贊
假設所有id屬性都遵循模式tr_XXXXXXX。此代碼將適用于它
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_code,'html.parser')
for t in soup.findAll('tr'):
print(t['id'][3:])
輸出
1599656
1599657
1599644
變量html_code包含您在問題中發布的一段html代碼
添加回答
舉報
0/150
提交
取消