2017-11-22 14 views
5

में खोजना मैं विकिपीडिया पर कुछ देशों की स्वतंत्रता तिथि को पकड़ने के लिए एक स्क्रिप्ट लिखता हूं।पायथन और सुंदर सूप: केवल एक निश्चित कक्षा

उदाहरण के लिए

, कज़ाकस्तान के साथ:

URL_QS = 'https://en.wikipedia.org/wiki/Kazakhstan' 
r = requests.get(URL_QS) 
soup = BeautifulSoup(r.text, 'lxml') 

# Only keep the infobox (top right) 
infobox = soup.find("table", class_="infobox geography vcard") 

if infobox: 
    formation = infobox.find_next(text = re.compile("Formation")) 

    if formation: 
     independence = formation.find_next(text = re.compile("independence")) 

     if independence: 
      independ_date = independence.find_next("td").text 
     else: 
      independence = formation.find_next(text = re.compile("Independence")) 

      if independence: 
       independ_date = independence.find_next("td").text 


print(independ_date) 

और मैं निम्नलिखित उत्पादन:

Almaty 

यह आउटपुट पाठ में, इन्फोबॉक्स में लेकिन उसके बाद स्थानीय नहीं है। ऐसा इसलिए है क्योंकि "formation.find_next (text = re.compile (" आजादी "))" को इन्फोबॉक्स के बाहर कुछ मिला लेकिन मुझे समझ में नहीं आया कि शोध केवल इन्फोबॉक्स में क्यों नहीं किया जाना चाहिए? मैं इस क्षेत्र में कैसे खोज सकता हूं?

आपकी मदद के लिए अग्रिम धन्यवाद!

+0

गठन = infobox.find_next (पाठ = re.compile ("संरचना")) आप इस लाइन की फिर से पुष्टि कर सकते हैं, क्योंकि यह चर गठन के लिए एक मूल्य "संरचना" लौटा रहा है, तो आप इसे प्रिंट । – kmcodes

उत्तर

1

क्योंकि "formation.find_next (पाठ = re.compile (" आजादी "))" केवल infobox geography vcard तत्व के अंदर खोज करने के लिए अपने soup.find() को .extract() जोड़ने इन्फोबॉक्स के बाहर

कुछ पाया यह है।

infobox = soup.find("table", class_="infobox geography vcard").extract()

0

आपका कोड पहले "independence" शब्द के बाद मूल्य के लिए खोज रहा था जो होना चाहिए दूसरा, यह भी, "Formation" स्ट्रिंग अच्छी तरह से सामान्य नहीं है के रूप में मैं कुछ देशों पर परीक्षण किया है, इसलिए मुझे लगता है कि आप शुरू से ही "Independence" पर खोज कर सकते हैं:

infobox = soup.find("table", class_="infobox geography vcard") 

if infobox: 
    formation = infobox.find_next(text = re.compile("Independence")) 

    if formation: 
     independence = formation.find_next(text = re.compile("independence")) 

     if independence: 
      independence = infobox.find_next(text = re.compile("Independence")) 
      independ_date = independence.find_next("td").text 

print(independ_date) 

यह स्वतंत्रता तिथि वाले किसी भी देश के विकिपीडिया पृष्ठ के स्वतंत्रता अनुभाग में पहली तारीख लौटाएगा।