2017-03-18 2 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は、私はそれが正常に動作し、全タグitem.find('lastmod')を印刷した場合のに対してはAttributeErrorをretuns。

「lastmod」タグの間のテキストは、各「item」内から取得したいと考えています。

おかげ

答えて

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  
関連する問題