2017-03-18 76 views
0

我目前正在解析這個url。 Url將成爲解析函數的參數。BeautifulSoup:提取標籤之間的字符串似乎不工作

def parse(sitemap): 
req = urllib.request.urlopen(sitemap) 
soup = BeautifulSoup(req, 'lxml') 
soup.prettify() 
inventory_url = [] 
inventory_url_set = set() 

for item in soup.find_all('url'): 
    print(item.find('lastmod')) 

    # print(item.find('lastmod').text) 
    inventory_url_set.add(item.find('loc').text) 

然而,item.find('lastmod').text retuns一個AttributeError,而如果我要打印整個標籤item.find('lastmod')它工作正常。

我只想從每個'item'中的'lastmod'標籤之間獲取文本。

感謝

回答

1

並不是所有的url條目包含lastmod,所以你需要測試這一點。如果你使用一個字典,你可以在lastmod存儲的值,並仍然具有如下獨特的URL中受益:

from bs4 import BeautifulSoup 
import urllib.request 

def parse(sitemap): 
    req = urllib.request.urlopen(sitemap) 
    soup = BeautifulSoup(req, 'lxml') 
    inventory_urls = {} 

    for url in soup.find_all('url'): 
     if url.lastmod: 
      lastmod = url.lastmod.text 
     else: 
      lastmod = None 

     inventory_urls[url.loc.text] = lastmod 

    for url, lastmod in inventory_urls.items(): 
     print(lastmod, url) 

parse("https://www.kith.com/sitemap_products_1.xml")   

這將使你在開始如下列表:

2017-02-12T03:55:25Z https://kith.com/products/adidas-originals-stan-smith-wool-pk-grey-white 
2017-03-13T18:55:24Z https://kith.com/products/norse-projects-niels-pocket-boucle-tee-black 
2017-03-15T17:20:47Z https://kith.com/products/ronnie-fieg-x-fracap-rf120-rust 
2017-03-17T01:30:25Z https://kith.com/products/new-balance-696-birch 
2017-01-23T08:43:56Z https://kith.com/products/ronnie-fieg-x-diamond-supply-co-x-asics-gel-lyte-v-1 
2017-03-17T00:41:03Z https://kith.com/products/off-white-diagonal-ferns-hoodie-black 
2017-03-16T15:01:55Z https://kith.com/products/norse-projects-skagen-bubble-crewneck-charcoal 
2017-02-21T15:57:56Z https://kith.com/products/vasque-eriksson-gtx-brown-black  
相關問題