2016-07-29 28 views
1

我怎麼會選擇所有的標題在此頁面如何在此html中選擇特定標籤?

http://bulletin.columbia.edu/columbia-college/departments-instruction/african-american-studies/#coursestext 

例如:我試圖讓所有類似這樣的臺詞:

AFAS C1001 Introduction to African-American Studies. 3 points. 

main_page通過所有的迭代從這裏學校上課,所以我可以抓住所有的標題像上面:

http://bulletin.columbia.edu/columbia-college/departments-instruction/ 

for page in main_page: 
    sub_abbrev = page.find("div", {"class": "courseblock"}) 

我有這樣的代碼,但我無法弄清楚到底如何選擇所有的(」第一個孩子的'強')標籤。 使用最新的蟒蛇和美麗的湯4網絡刮。 如果還有其他需要的東西,請立即行動。 謝謝

回答

3

courseblock類對元素進行迭代,然後,對於每個課程,獲取具有courseblocktitle類的元素。使用工作示例select() and select_one() methods

import requests 
from bs4 import BeautifulSoup 


url = "http://bulletin.columbia.edu/columbia-college/departments-instruction/african-american-studies/#coursestext" 
response = requests.get(url) 
soup = BeautifulSoup(response.content, "html.parser") 

for course in soup.select(".courseblock"): 
    title = course.select_one("p.courseblocktitle").get_text(strip=True) 
    print(title) 

打印:

AFAS C1001 Introduction to African-American Studies.3 points. 
AFAS W3030 African-American Music.3 points. 
AFAS C3930 (Section 3) Topics in the Black Experience: Concepts of Race and Racism.4 points. 
AFAS C3936 Black Intellectuals Seminar.4 points. 
AFAS W4031 Protest Music and Popular Culture.3 points. 
AFAS W4032 Image and Identity in Contemporary Advertising.4 points. 
AFAS W4035 Criminal Justice and the Carceral State in the 20th Century United States.4 points. 
AFAS W4037 (Section 1) Third World Studies.4 points. 
AFAS W4039 Afro-Latin America.4 points. 

從@double_j良好的後續問題:

在OPS例子,他有之間的空間點。你會如何保持這一點?這就是數據在網站上的顯示方式,甚至認爲它並不在源代碼中。

我雖然有關使用get_text() methodseparator的說法,但也將在最後一個點前添加一個額外的空間。相反,我會通過str.join()加入strong元素文本:

for course in soup.select(".courseblock"): 
    title = " ".join(strong.get_text() for strong in course.select("p.courseblocktitle > strong")) 
    print(title) 
+0

在OPS例子,他有兩點之間的空間。你會如何保持這一點?這就是數據在網站上的顯示方式,甚至認爲它並不在源代碼中。 –

+0

@double_j很好的發現!在答案中解釋。謝謝! – alecxe