-1

我正在寻求一些帮助,使我的 if 语句对这篇文章的底部“更严格”,这样它就不会意外返回错误的数据。

打印details

<li class="">
<span class="prefix">Student Discount</span>
                £2922.70                </li>
<li class="">
<span class="prefix">Student DiscountX</span>
                5499.99                </li>

打印细节

<li class="">
<span class="prefix">Student Discount</span>
                £2922.70                </li>

打印 unicode(详细)

<li class="">
<span class="prefix">Student Discount</span>
                £2922.70                </li>

BeautifulSoup 代码片段

details = details_section.findAll('li', {"class":"full"})
for detail in details:
    if detail.find(text=re.compile("Student Discount")):
        SD = detail.get_text().replace("Student Discount", "").strip().replace(u"£", "POUNDSIGNHERE")
        SD = "Student Discount {}".format(detail.get_text().replace("Student Discount", "").strip().replace(u"£", "POUNDSIGNHERE"))
        if not "Student Discount POUNDSIGNHERE" in result_SF:
            SD = "Student Discount POUNDSIGNHERE{}".format(detail.get_text().replace("Student Discount", "").strip().replace(u"£", "POUNDSIGNHERE"))  
        print SD

输出

SF POUNDSIGNHERE2922.70
SF POUNDSIGNHERE5499.99

正如你所看到的,我已经解决了每个细节中有太多空格/制表符的问题,并且我已经用英镑符号替换了,POUNDSIGNHERE以便稍后当我需要它时,我所要做的就是用英镑替换它象征。

我正在发布寻找一些帮助更改:
if detail.find(text=re.compile("Student Discount")):
到类似:
if detail.find(text=re.compile('<span class="prefix">Student Discount</span>')):
甚至:
if detail.find(text=re.compile('>Student Discount<')):

我想让 if 语句更严格,这样它就不会潜在地拾取如下行:

<li class="">
<span class="prefix">Student Discount Old</span>
                £2922.70                </li>

任何想法、建议或想法将不胜感激。

4

1 回答 1

1

只使用一个正则表达式。使用条带、替换等是不必要的,并且像这样链接它们是令人困惑的。

import re
details = details_section.findAll('li', {"class":"full"})
for detail in details:
    detail_text = detail.get_text()
    m = re.match(r"\s*Student Discount\s+£\s*(\d+\.\d+)\s*", detail_text)
    if m:
        discount_value = m.group(1)
        print "discount = " + discount_value
于 2013-10-25T17:44:47.147 回答