【问题标题】:How to select a specific tag within this html?如何在此 html 中选择特定标签?
【发布时间】:2016-07-29 16:08:39
【问题描述】:

如何选择此页面中的所有标题

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"})

我有这段代码,但我不知道如何选择第一个孩子的所有(“强”)标签。 使用最新的 python 和美丽的汤 4 进行网页抓取。 Lmk 如果还有其他需要的话。 谢谢

【问题讨论】:

    标签: python html web-scraping beautifulsoup html-parsing


    【解决方案1】:

    遍历带有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 的一个很好的后续问题:

    在 OP 示例中,他在点之间有一个空格。你会如何保持它?这就是数据在网站上的显示方式,即使它不是真正的源代码。

    我虽然关于使用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)
    

    【讨论】:

    • 在 OPs 示例中,他在点之间有一个空格。你会如何保持它?这就是数据在网站上的显示方式,即使它不是真正的源代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多