只需要链接作为输出

时间:2016-10-12 11:26:34

标签: python python-2.7 beautifulsoup data-cleansing

我有多个html标签我只想提取第一个href =" ..."的内容例如,这一行数据。

<a class="product-link" data-styleid="1424359" href="/tops/biba/biba-beige--pink-women-floral-print-top/1424359/buy?src=search"><img _src="http://assets.myntassets.com/h_240,q_95,w_180/v1/assets/images/1424359/2016/9/28/11475053941748-BIBA-Beige--Pink-Floral-Print-Kurti-7191475053941511-1_mini.jpg" _src2="http://assets.myntassets.com/h_307,q_95,w_230/v1/assets/images/1424359/2016/9/28/11475053941748-BIBA-Beige--Pink-Floral-Print-Kurti-7191475053941511-1_mini.jpg" alt="BIBA Beige &amp; Pink Women Floral Print Top" class="lazy loading thumb" onerror="this.className='thumb error'" onload="this.className='thumb'"/><div class="brand">Biba</div><div class="product">Beige &amp; Pink Women Floral Print Top</div><div class="price">Rs. 899</div><div class="sizes">Sizes: S, L, XL, XXL</div></a>

我只想/tops/biba/biba-beige--pink-women-floral-print-top/1424359/buy?src=search作为输出

代码如下:

from bs4 import BeautifulSoup
import urllib

x=urllib.urlopen("http://www.myntra.com/tops-tees-menu/")
soup2 = BeautifulSoup(x, 'html.parser')
for i in soup2.find_all('a', attrs={'class': 'product-link'}):
    print i
    print i.find('a')['href']

1 个答案:

答案 0 :(得分:0)

如果您需要一个“产品链接”,请使用find()

soup2.find('a', attrs={'class': 'product-link'})["href"]

请注意,您也可以使用CSS selector定位技术:

soup2.select_one('a.product-link')["href"]