2016-06-05 10 views
0

Ich bin ein Neuling. Ich habe eine Funktion erstellt, die zwischen einer bestimmten Anzahl von Posts kratzt. Es funktioniert, aber es scheint nur so groß und Anfänger zu suchen. Ich möchte den Code verdichten und ihn so verhalten, dass er die Anzahl der abgeschriebenen Beiträge um 1 verringert, wenn der anfängliche Betrag zu groß ist. Wenn es also versucht, 15 zu kratzen und es nur 14 gibt, wird es auf 14 fallen, anstatt zu stoppen. heres mein CodeWie kann ich meine Python Scraping-Funktion zwischen einem bestimmten Bereich von Post ausführen?

def scrape_world(): 
    url = 'http://www.example.org' 
    html = requests.get(url, headers=headers) 
    soup = BeautifulSoup(html.text, 'html5lib') 
    titles = [] 

    if len(titles) > 15: 
     titles = soup.find_all('section', 'box')[:15] 
     random.shuffle(titles) 
     print(len(titles)) 

    elif len(titles) > 14: 
     titles = soup.find_all('section', 'box')[:14] 
     # random.shuffle(titles) 
     print(len(titles)) 

    elif len(titles) > 13: 
     titles = soup.find_all('section', 'box')[:13] 
     random.shuffle(titles) 
     print(len(titles)) 

    elif len(titles) > 12: 
     titles = soup.find_all('section', 'box')[:12] 
     random.shuffle(titles) 
     print(len(titles)) 

    elif len(titles) > 11: 
     titles = soup.find_all('section', 'box')[:11] 
     random.shuffle(titles) 
     print(len(titles)) 

    elif len(titles) > 10: 
     titles = soup.find_all('section', 'box')[:10] 
     random.shuffle(titles) 
     print(len(titles)) 

    elif len(titles) > 9: 
     titles = soup.find_all('section', 'box')[:9] 
     random.shuffle(titles) 
     print(len(titles)) 

    else: 
     titles = soup.find_all('section', 'box')[:8] 
     random.shuffle(titles) 
     print(len(titles)) 

    entries = [{'href': url + box.a.get('href'), 
       'src': box.img.get('src'), 
       'text': box.strong.a.text, 
       } for box in titles] 

    # random.shuffle(entries) 

    return entries 

Ich habe versucht, so etwas wie

if len(titles) > 15 || < 9: 

aber das hat nicht funktioniert richtig

UPDATE: print (Titel) Ausgabe

[<section class="box"> 
<a class="video-box" href="/videos/video.php?v=wshh2Nw4BKk0vav380lx"> 
<img alt="" height="125" src="http://i.ytimg.com/vi/clPaWvb6lWk/maxresdefault.jpg" width="222"/> 
</a> 
<strong class="title"><a href="/videos/video.php?v=wshh2Nw4BKk0vav380lx">Spodee - All I Want</a></strong> 
<div> 
<span class="views">18,781</span> 
<span class="comments"><a data-disqus-identifier="95018" href="http://www.worldstarhiphop.com/videos/video.php?v=wshh2Nw4BKk0vav380lx#disqus_thread"></a></span> 
</div> 
</section>, <section class="box"> 
<a class="video-box" href="/videos/video.php?v=wshh058e7C1B1Ey8qwNT"> 
<img alt="" height="125" src="http://hw-static.worldstarhiphop.com/u/pic/2016/06/t9OWyXfcdYQm.jpg" width="222"/> 
</a> 
<strong class="title"><a href="/videos/video.php?v=wshh058e7C1B1Ey8qwNT">Sheesh: Dude Grill Is On Another Level!</a></strong> 
<div> 
<span class="views">182,832</span> 
<span class="comments"><a data-disqus-identifier="95013" href="http://www.worldstarhiphop.com/videos/video.php?v=wshh058e7C1B1Ey8qwNT#disqus_thread"></a></span> 
</div> 
</section>, <section class="box"> 
<a class="video-box" href="/videos/video.php?v=wshhrXYCnHFIj4h2GQjE"> 
<img alt="" height="125" src="http://hw-static.worldstarhiphop.com/u/pic/2016/06/M1itOMKyh7zj.jpg" width="222"/> 
</a> 
<strong class="title"><a href="/videos/video.php?v=wshhrXYCnHFIj4h2GQjE">Back At It: Brock Lesnar To Return At UFC 200, WWE Approved!</a></strong> 
<div> 
<span class="views">124,237</span> 
<span class="comments"><a data-disqus-identifier="95016" href="http://www.worldstarhiphop.com/videos/video.php?v=wshhrXYCnHFIj4h2GQjE#disqus_thread"></a></span> 
</div> 
</section>, <section class="box"> 
<a class="video-box" href="/videos/video.php?v=wshhj7V8H8GXx08iH2V9"> 
<img alt="" height="125" src="http://i.ytimg.com/vi/YRlsJtuZ09s/maxresdefault.jpg" width="222"/> 
</a> 
<strong class="title"><a href="/videos/video.php?v=wshhj7V8H8GXx08iH2V9">Jose Guapo - Off Top</a></strong> 
<div> 
<span class="views">16,462</span> 
<span class="comments"><a data-disqus-identifier="95017" href="http://www.worldstarhiphop.com/videos/video.php?v=wshhj7V8H8GXx08iH2V9#disqus_thread"></a></span> 
</div> 
</section>, <section class="box"> 
<a class="video-box" href="/videos/video.php?v=wshhfOnhy45f780tHqQG"> 
<img alt="" height="125" src="http://hw-static.worldstarhiphop.com/u/pic/2016/06/wn03kuXW3v2a.jpg" width="222"/> 
</a> 
<strong class="title"><a href="/videos/video.php?v=wshhfOnhy45f780tHqQG">Tulsa Candidate Angry About Not Being Involved In The Mayoral Debate, Runs Up There Anyway!</a></strong> 
<div> 
<span class="views">115,333</span> 
<span class="comments"><a data-disqus-identifier="95014" href="http://www.worldstarhiphop.com/videos/video.php?v=wshhfOnhy45f780tHqQG#disqus_thread"></a></span> 
</div> 
</section>, <section class="box"> 
<a class="video-box" href="/videos/video.php?v=wshhrYcD83QWN1n0665g"> 
<img alt="" height="125" src="http://hw-static.worldstarhiphop.com/u/pic/2016/06/14H17jc8ZTIw.jpg" width="222"/> 
</a> 
<strong class="title"><a href="/videos/video.php?v=wshhrYcD83QWN1n0665g">This Motel Has An Interesting Key Policy!</a></strong> 
<div> 
<span class="views">16,015</span> 
<span class="comments"><a data-disqus-identifier="95019" href="http://www.worldstarhiphop.com/videos/video.php?v=wshhrYcD83QWN1n0665g#disqus_thread"></a></span> 
</div> 
</section>, <section class="box"> 
<a class="video-box" href="/videos/video.php?v=wshhs2kTRq49K0gXYbuu"> 
<img alt="" height="125" src="http://hw-static.worldstarhiphop.com/u/pic/2016/06/e2VMzdzmKwFe.jpg" width="222"/> 
</a> 
<strong class="title"><a href="/videos/video.php?v=wshhs2kTRq49K0gXYbuu">Yonio &amp; AG - Holy (Freestyle) [Houston Unsigned Artist] </a></strong> 
<div> 
<span class="views">4,076</span> 
<span class="comments"><a data-disqus-identifier="95012" href="http://www.worldstarhiphop.com/videos/video.php?v=wshhs2kTRq49K0gXYbuu#disqus_thread"></a></span> 
</div> 
</section>, <section class="box"> 
<a class="video-box" href="/videos/video.php?v=wshhDQZ3eC6yJE6Y5hjL"> 
<img alt="" height="125" src="http://hw-static.worldstarhiphop.com/u/pic/2016/06/dVjLEzVRc1YQ.jpg" width="222"/> 
</a> 
<strong class="title"><a href="/videos/video.php?v=wshhDQZ3eC6yJE6Y5hjL">Messed Up: 6-Year Old Polish Boy Beats His Mother And Pulls Her Hair!</a></strong> 
<div> 
<span class="views">201,996</span> 
<span class="comments"><a data-disqus-identifier="95015" href="http://www.worldstarhiphop.com/videos/video.php?v=wshhDQZ3eC6yJE6Y5hjL#disqus_thread"></a></span> 
</div> 
</section>] 
+1

Keine Ihrer Kriterien werden hier erfüllt werden. Du definierst 'titles = []' vor deinem ersten 'if'check ... na' len (titles) 'ist null und da dies niemals eines deiner Kriterien erfüllt, fällt es einfach durch. Warum versuchen Sie, die Länge von 'titles' zu prüfen, bevor Sie sie als' titles = soup.find_all ('section', 'box') definieren ''? – roganjosh

+0

@roganjosh Wenn ich es ursprünglich so definiert hatte 'titles = soup.find_all (' section ',' box ') [: 15]' aber es hat nichts geschabt, also musste ich die Zahlen manuell verkleinern, um zu sehen, wie die Nummer war. Es stellte sich heraus, dass es 8 war. Ich dachte, dass das Setup, das ich hatte, dieses Problem gelöst hätte, aber es hat nicht funktioniert. Also habe ich titles = [] geändert und es hat funktioniert – losee

+0

Ich bin mir ziemlich sicher, dass es nicht funktioniert, wie du denkst. Da 'titles = []' eine Länge von Null hat, wird _alles_ durch die Kriterien geleitet, die für Ihr 'else' definiert sind. Ich habe keine Erfahrung mit BeautifulSoup, aber es fühlt sich nicht intuitiv an, dass Sie die Anzahl der erwarteten Matches vor dem Scraping definieren müssen. Außerdem ist "[: 15]" ein Listen-Slice. Wenn Sie also ein Listenobjekt an Sie zurückgibt, ändert dieser Befehl nichts daran, wie viel Scraped ist, sondern nur die Anzahl der Elemente in der Liste, die für Sie sichtbar sind. – roganjosh

Antwort

2

Es ist immer besser in Ihrem Beispiel ist tatsächlich das Beispiel von dem, was Sie versuchen, so zu tun, dass es einfacher ist, für Leute, Ihr Problem repro.

Wie die Kommentare sagen, Ihr Code gerade zu titles[:8] wird, weil vor der Schleife, titles =[] was bedeutet, len(titles) 0 ist die soup.find_all Funktion intelligent genug, um zu wissen, wie groß Ihre Datenmenge ist, so dass keine Notwendigkeit, die Länge angeben. Basierend auf Ihrer print(titles) Ausgabe, nahm ich an, dass Sie Ihren Code auf url = 'http://www.worldstarhiphop.com' zeigen, so dass der folgende verwendet. Wenn Sie diese spezifische URL scrapen, gibt es ein "SENDEN SIE IHR VIDEO" -Ergebnis in titles[11], das einen Fehler verursacht, wenn Sie Ihr entries Wörterbuch erstellen. roganjosh 's Antwort ist der richtige grundlegende Ansatz, aber in diesem Fall wird es nicht Titel erfassen [11], die nicht None ist, aber leider nur ein anderes Format. Wenn du "cleaned_titles" aktualisierst, sollte es für dich funktionieren.

cleaned_titles = [title for title in titles if title.a.get('href') != 'vsubmit.php'] 

geben Sie:

def scrape_world(): 
    url = 'http://www.worldstarhiphop.com' 
    html = requests.get(url, headers=headers) 
    soup = BeautifulSoup(html.text, 'html5lib') 
    titles = soup.find_all('section', 'box') 

    cleaned_titles = [title for title in titles if title.a.get('href') != 'vsubmit.php'] 

    entries = [{'href': url + box.a.get('href'), 
       'src': box.img.get('src'), 
       'text': box.strong.a.text, 
       } for box in cleaned_titles] 
    return entries 
+0

hinzugefügt Das ist ein paar gute Ermittlungsarbeit, Bravo :) – roganjosh

+0

@Matt Das hat besser funktioniert als ich erwartet hatte. Es kratzt so sehr, dass ich jetzt ein Limit setzen muss, danke. Jetzt kann ich all diese if-Anweisungen entfernen – losee

1

Ok, BeautifulSoup kehrt ein andere Art von Struktur als ich erwartet hatte. Ich habe jedoch auf die Prämisse einer Antwort gedrängt, um sie zu klären, also poste ich und ziehe mich zurück, wenn es ein Problem damit gibt.

def scrape_world(): 
    url = 'http://www.example.org' 
    html = requests.get(url, headers=headers) 
    soup = BeautifulSoup(html.text, 'html5lib') 
    titles = soup.find_all('section', 'box') 

    cleaned_titles = [title for title in titles if title is not None] 

    entries = [{'href': url + box.a.get('href'), 
       'src': box.img.get('src'), 
       'text': box.strong.a.text, 
       } for box in cleaned_titles] 
    return entries