python - 如何在该 html 中选择特定标签?

标签 python html web-scraping beautifulsoup html-parsing

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

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

例如:我正在尝试获取与此类似的所有行:

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

main_page 正在迭代这里的所有学校类(class),因此我可以获取上面的所有标题:

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

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

我有这段代码,但我无法确切地弄清楚如何选择第一个 child 的所有(“强”)标签。 使用最新的 python 和 beautiful soup 4 进行网页抓取。 Lmk 如果还有什么需要的。 谢谢

最佳答案

使用 courseblock 类迭代元素,然后对于每门类(class),获取使用 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 提出的一个很好的后续问题:

In the OPs example, he has a space between the points. How would you keep that? That's how the data shows on the site, even thought it's not really in the source code.

我想使用 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)

关于python - 如何在该 html 中选择特定标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38663186/

相关文章:

python - 可视化未出现在 Tensorflow-PyCharm IDE 中

PythonAnywhere 试图上传我的网站

python - 使用 Wand + ImageMagick 调整 GIF 大小

html - 如何使文本自动收缩以适应 div?

javascript - 如何在 typescript 中突出显示选项卡菜单中的事件选项卡

web-scraping - Python 3.7-PhantomJS-Driver.get(url) 与 'Window handle/name is invalid or closed?'

python - 在 tensorflow 对象检测模型的训练数据集中重复图像

jquery - 使用 jQuery,如何打开/关闭内容之间的 div?

python-3.x - 从 Div 标签中提取文本数据,而不是从子 H3 标签中提取文本数据

python - 使用 python selenium 的网页抓取问题