2017-07-28 8 views
-1

Die verschachtelte Schleife mit der Variablen j funktioniert nicht. Der Debugger überspringt ihn, obwohl die Variablen benötigt werden, bevor er richtig initialisiert zu sein scheint.Python, Web Scraping: geschachtelte Schleife funktioniert nicht

from urllib.request import Request, urlopen 
# Get beautifulsoup4 with: pip install beautifulsoup4 
import bs4 
import pdb 
import sys 
import json 

site = "http://bgp.he.net/report/world" 
hdr = {'User-Agent': 'Mozilla/5.0'} 
req = Request(site,headers=hdr) 
page = urlopen(req) 
soup = bs4.BeautifulSoup(page, 'html.parser') 

for t in soup.find_all('td', class_='centeralign'): 
    s = str(t.string) 
    if s != "None": 
     print (s.strip()) 
     site2 = "http://bgp.he.net/country/" + s.strip() 
     req = Request(site2,headers=hdr) 
     soup2 = bs4.BeautifulSoup(page, 'html.parser') 

    for j in soup2.find_all('td'): 
     s2 = str(j.string) 
     print (j.strip()) 
+0

welche Ausgabe Sie wollen? – Gahan

+0

auch Sie versuchen, die gleiche Seite immer wieder zu analysieren. – Gahan

+1

Mögliches Duplikat von [Extrahieren von Informationen aus einer Tabelle außer Kopfzeile der Tabelle mit bs4] (https://stackoverflow.com/questions/37635847/extracting-information-from-a-table-except-header-of-the-table -using-bs4) – stovfl

Antwort

0
from urllib.request import Request, urlopen 
# Get beautifulsoup4 with: pip install beautifulsoup4 
import bs4 
import pdb 
import sys 
import json 

site = "http://bgp.he.net/report/world" 
hdr = {'User-Agent': 'Mozilla/5.0'} 
req = Request(site,headers=hdr) 
page = urlopen(req) 
soup = bs4.BeautifulSoup(page, 'html.parser') 

for t in soup.find_all('td', class_='centeralign'): 
    s = str(t.string) 
    if s != "None": 
     print(s.strip()) 
     site2 = "http://bgp.he.net/country/" + s.strip() 
     req2 = Request(site2,headers=hdr) # you missed these two lines 
     page2 = urlopen(req2) 
     soup2 = bs4.BeautifulSoup(page2, 'html.parser') 

     for j in soup2.find_all('td'): 
      s2 = str(j.text) 
      print(s2.strip()) # wrong variable used by you to strip 
+0

Danke, ich fühle mich wie ein Idiot –