2016-04-14 19 views
1

Bir haber sayfasının En Çok Okunan bölümündeki başlıkları ayıklamak istiyorum. Şimdiye kadar sahip olduğum şey bu, ama tüm başlıkları alıyorum. Sadece En Çok Okunanlar bölümündekileri istiyorum. Çoğu okunan makaleler için sadece div konteyner için kapsamını sınırlamak gerekirÇoğu Okuma Başlığını BS4 ile Ayıklanıyor

import requests 
from bs4 import BeautifulSoup 

base_url = 'https://www.michigandaily.com/section/opinion' 
r = requests.get(base_url) 
soup = BeautifulSoup(r.text, "html5lib") 

for story_heading in soup.find_all(class_= "views-field views-field-title"): 
    if story_heading.a: 
     print(story_heading.a.text.replace("\n", " ").strip()) 
    else: 
     print(story_heading.contents[0].strip())` 

cevap

1

`

.

import requests 
from bs4 import BeautifulSoup 

base_url = 'https://www.michigandaily.com/section/opinion' 
r = requests.get(base_url) 
soup = BeautifulSoup(r.text, "html5lib") 

most_read_soup = soup.find_all('div', {'class': 'view-id-most_read'})[0] 

for story_heading in most_read_soup.find_all(class_= "views-field views-field-title"): 
    if story_heading.a: 
     print(story_heading.a.text.replace("\n", " ").strip()) 
    else: 
     print(story_heading.contents[0].strip()) 
0

Üst En çok okunan div gelen özel etiketleri almak için bir css seçici kullanabilirsiniz:

from bs4 import BeautifulSoup 

base_url = 'https://www.michigandaily.com/section/opinion' 
r = requests.get(base_url) 
soup = BeautifulSoup(r.text, "html5lib") 
css = "div.pane-most-read-panel-pane-1 a" 
links = [a.text.strip() for a in soup.select(css)] 

verecek Hangi:

[u'Michigan in Color: Anotha One', u'Migos trio ends 2016 SpringFest with Hill Auditorium concert', u'Migos dabs their way to a seminal moment for Ann Arbor hip hop', u'Best of Ann Arbor 2016', u'Best of Ann Arbor 2016: Full List'] 
İlgili konular