【发布时间】: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