2016-10-16 196 views
1

如果該項目沒有文本,我試圖獲取HTML標籤。例如:我正在循環所有「a」屬性(URL)。
但是,一些網址中有文字,有些則沒有。
在這種情況下,我正在嘗試獲取沒有文字的網址。
因此,我做了這樣的事情。如何獲取特定的HTML標籤

response = requests.get('https://fw.tmall.com/tmall/ser/tmall_detail.htm?spm=a1z1g.2177293.0.0.qF9gPO&service_code=ts-4078').text 
soup = BeautifulSoup(response) 
main_wrapper = soup.find('div',attrs={'id':'success-case'}).findAll('a') 
for items in main_wrapper: 
    dictionary = {} 
    href = items['href'] 
    if items.string is None: 
     print items['href'] 
    else: 
     print items.string 

我怎麼做,這樣if items.string is None:,而不是獲得該項目特定的URL所有的網址是什麼?

+0

你可以嘗試澄清?你有什麼?你想得到什麼? –

+0

我想要獲取特定的HTML屬性,在這種情況下,如果元素沒有文本,它將是中的IMG URL。 – Dilli

回答

0

我試圖讓那些沒有文字上

你可以使用列表修真者的URL

hrefs = [a['href'] for a in main_wrapper if a.string is None] 

獲得該項目特定只有網址而不是所有的網址!

不清楚這意味着什麼。每個a標籤只有一個特定的URL。你迭代的a標籤列表,所以你得到的網址

我希望得到特定HTML屬性的列表,在這種情況下,這將是IMG URL這裏面<a>

然後你需要環路內的另一個find方法提取出該<img>元素得到src屬性

+0

甜!謝謝:) – Dilli

+0

歡迎。您可以使用帖子旁邊的複選標記來顯示您的感謝。 –

0

我相信你正設法從無序列表獨特的錨裏面你的div。你可以看到每個錨具有獨特的類,rel-ink VS rel-name

<a href="//store.taobao.com/shop/view_shop.htm?user_number_id=2469022358" target="_blank" class="rel-ink"><img alt="NIHAOMARKET官方海外旗艦店" src="//img.alicdn.com/top/i1/TB1urimJFXXXXabaXXXwu0bFXXX.png" class="rel-img"></a> 
<a href="//store.taobao.com/shop/view_shop.htm?user_number_id=2469022358" target="_blank" class="rel-name">NIHAOMARKET官方海外旗艦店</a> 

所以,你可以使用錨類名第一錨每個李裏REL-墨讓他們:

urls =[a["href"] for a in soup.find('div', id="success-case").find_all("a",class_="rel-ink")] 

或使用CSS選擇

urls = [a["href"] for a in soup.select("#success-case ul li a.rel-ink")] 

兩者都會給你:

['//store.taobao.com/shop/view_shop.htm?user_number_id=692020965', '//store.taobao.com/shop/view_shop.htm?user_number_id=2087799889', '//store.taobao.com/shop/view_shop.htm?user_number_id=2469022358', '//store.taobao.com/shop/view_shop.htm?user_number_id=377676745', '//store.taobao.com/shop/view_shop.htm?user_number_id=2367059695', '//store.taobao.com/shop/view_shop.htm?user_number_id=449764134', '//store.taobao.com/shop/view_shop.htm?user_number_id=698389964', '//store.taobao.com/shop/view_shop.htm?user_number_id=509711360', '//store.taobao.com/shop/view_shop.htm?user_number_id=692020965', '//store.taobao.com/shop/view_shop.htm?user_number_id=1125022434', '//store.taobao.com/shop/view_shop.htm?user_number_id=1071997040', '//store.taobao.com/shop/view_shop.htm?user_number_id=795947607', '//store.taobao.com/shop/view_shop.htm?user_number_id=509711360', '//store.taobao.com/shop/view_shop.htm?user_number_id=692020965', '//store.taobao.com/shop/view_shop.htm?user_number_id=1071997040', '//store.taobao.com/shop/view_shop.htm?user_number_id=509711360', '//store.taobao.com/shop/view_shop.htm?user_number_id=377676745', '//store.taobao.com/shop/view_shop.htm?user_number_id=2367059695', '//store.taobao.com/shop/view_shop.htm?user_number_id=2469022358']