如何使用beauthoulsoup/python解析html?

2024-04-24 09:36:02 发布

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

如何使用beauthoulsoup解析date start和date end值?在

<h2 name="PRM-013113-21017-0FSNS" class="pointer">
    <a name="PRM-013113-21017-0FSNS">Chinese New Year Sale<br>
       <span>February 8, 2013 - February 10, 2013</span>
    </a>
</h2>

Tags: namenewdateh2saleyearstartclass
1条回答
网友
1楼 · 发布于 2024-04-24 09:36:02

像这样。在

import re
from BeautifulSoup import BeautifulSoup

html = '<h2 name="PRM-013113-21017-0FSNS" class="pointer"><a name="PRM-013113-21017-0FSNS">Chinese New Year Sale<br><span>February 8, 2013 - February 10, 2013</span></a></h2>'
date_span = BeautifulSoup(html).findAll('h2', {'class' : 'pointer'})[0].findAll('span')[0]
date = re.findall(r'<span>(.+?)</span>', str(date_span))[0]

(注意:您还可以使用beauthoulsoup的text=True方法和findAll一起使用来获得文本,而不是使用如下的regex。)

^{pr2}$

更新::

要将开始日期和结束日期作为单独的变量,您可以简单地将它们拆分,只需将日期变量拆分如下:

from BeautifulSoup import BeautifulSoup

html = '<h2 name="PRM-013113-21017-0FSNS" class="pointer"><a name="PRM-013113-21017-0FSNS">Chinese New Year Sale<br><span>February 8, 2013 - February 10, 2013</span></a></h2>'
date = BeautifulSoup(test).findAll('h2', {'class' : 'pointer'})[0].findAll('span')[0]
date = date.findAll(text=True)[0]
# Get start and end date separately
date_start, date_end = date.split(' - ')

现在,date_start变量包含开始日期,date_end变量包含结束日期。在

相关问题 更多 >