2016-12-31 6 views
1

を発見された行に等しい変数の設定:キーワードとのリンクが発見されるまで私は、トラブル正しいキーワードは次のコードで発見されたリンク印刷抱えていたキーワードが

import urllib2 
from random import randint 
import time 
from lxml import etree 
from time import sleep 

a = requests.get('http://properlbc.com/sitemap.xml') 
#time.sleep(1) 
scrape = BeautifulSoup(a.text, 'lxml') 
linkz = scrape.find_all('loc') 
for linke in linkz: 
    if "products" in linke.text: 
     sitemap = str(linke.text) 
     break 



while True: 
# sleep(randint(4,6)) 
    keyword1 = "properlbc" 
    keyword2 = "products" 
    keyword3 = "bb1296" 
    r = requests.get(sitemap) 
# time.sleep(1) 
    soup = BeautifulSoup(r.text, 'lxml') 
    links = soup.find_all('loc') 
    for link in links: 
     while (keyword1 in link.text and keyword2 in link.text and keyword3 in link.text): 
      continue 
     print("LINK SCRAPED") 
     print(str(link.text) + "link scraped") 
     break 

コードがループに成功していますしかし、それはキーワードで特定のリンクを表示しませんあなたが

for link in links: 
    if keyword1 in link.text and keyword2 in link.text and keyword3 in link.text: 
     print("LINK SCRAPED") 
     print(str(link.text) + "link scraped") 

をしなければならない代わりに「https://properlbc.com/collections/new-arrival/products/bb1296

+0

を見つけたときにループを残します。 – furas

答えて

1

の「link.text」、それは最初のを印刷しますあるいは

for link in links: 
    text = link.text 
    if keyword1 in text and keyword2 in text and keyword3 in text: 
     print("LINK SCRAPED") 
     print(text, "link scraped") 

EDIT:それはあなたが `while`と、それはそれを印刷しないように、キーワードとリンクをスキップする` continue`を使用したリンク

keyword1 = "properlbc" 
keyword2 = "products" 
keyword3 = "bb1296" 

found = False 

while not found: 
    #sleep(randint(4,6)) 
    r = requests.get(sitemap) 
    soup = BeautifulSoup(r.text, 'lxml') 
    links = soup.find_all('loc') 
    for link in links: 
     text = link.text 
     if keyword1 in text and keyword2 in text and keyword3 in text: 
      print("LINK SCRAPED") 
      print(text, "link scraped") 
      found = True # to leave `while` loop 
      break # to leave `for` loop 
+0

リンクはサイトに追加されるまでループしますか? – ColeWorld

+0

にリンクが追加されているかどうかを確認するには、もう一度ページを読む必要があります。リンクのみをループするのは役に立たない。 – furas

+0

がリンクを見つけたときにループを終了するには 'while True'の代わりに' found = False'と 'not found:'を使うことができます。後で 'found = True'を' if keyword1 ... 'の中に設定します。 – furas

関連する問題