【问题标题】:Print just first output line只打印第一行输出
【发布时间】:2015-09-29 19:25:22
【问题描述】:

我编写了一个代码,它从指定的 url 中提取某些文本,但它给了我 2 或 3 个(取决于网页)不同行的后续相同输出。我只需要使用第一个输出。我该怎么做? 这是我的代码:-

 import requests, re
 from bs4 import BeautifulSoup
 url="http://www.barneys.com/raf-simons-%22boys%22-poplin-shirt-504182589.html#start=2"
 r=requests.get(url)
 soup=BeautifulSoup(r.content)
 links=soup.find_all("a")
 g_d4=soup.find_all("ol", {"class":"breadcrumb"})
 for item in g_d4:
      links_2=soup.find_all('a', href=re.compile('^http://www.barneys.com/barneys-new-york/men/'))
      pattern_2=re.compile("clothing/(\w+)")
      for link in links_2:
          match_1=pattern_2.search(link["href"])
          if match_1:
             print (match_1.group(1))

我的输出是:

         shirts
         shirts
         shirts

我希望我的输出像这样:

         shirts

我该怎么办?

【问题讨论】:

    标签: python regex python-2.7 web-scraping beautifulsoup


    【解决方案1】:

    不知道你需要哪个答案,所以我两个都回答。

    独特的结果

    如果您想要整个页面的独特结果,您可以使用集合来执行以下操作:

    for item in g_d4:
        links_2=soup.find_all('a', href=re.compile('^http://www.barneys.com/barneys-new-york/men/'))
        pattern_2=re.compile("clothing/(\w+)")
        matches = set()
        for link in links_2:
            match_1=pattern_2.search(link["href"])
            if match_1:
                matches.add(match_1.group(1))
        print(matches)
    

    单个结果

    如果您只想要每次迭代中的第一个结果,您可以在内部循环中中断:

    for item in g_d4:
        links_2=soup.find_all('a', href=re.compile('^http://www.barneys.com/barneys-new-york/men/'))
        pattern_2=re.compile("clothing/(\w+)")
        for link in links_2:
            match_1=pattern_2.search(link["href"])
            if match_1:
                print(match_1.group(1))
                break
    

    【讨论】:

    • 是的,这就是我想要的。谢谢!
    猜你喜欢
    • 2014-03-16
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    相关资源
    最近更新 更多