2016-07-29 3 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를 사용하여 웹 스크래핑하기. 필요한 것이 있으면 Lmk하십시오. 감사합니다.

답변

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

을, 그는 점 사이의 공간이 마련되어 있습니다. 너 어떻게 지켜 줄거야? 이것이 사이트에 데이터가 표시되는 방식이며 소스 코드에 실제로 포함되지는 않는다고 생각합니다. –

+0

@double_j 좋은 결과! 대답에 답변. 감사! – alecxe