首页 > 解决方案 > 使用 BeautifulSoup 在 Python 中抓取特定的 div

问题描述

我目前正在尝试从网页(https://www1.president.go.kr/articles/8863)中抓取文本数据。我想要的部分位于[[[div class="text left cb text_wrap motion fadeIn visible" data-animation="fadeIn"]]]. 我已经尝试过soup.find('div', {'class' :'text left cb text_wrap motion fadeIn visible'})了,但我什么也没得到。

response = requests.get('https://www1.president.go.kr/articles/8863')
if response.status_code == 404:
    print('404: A page could not load')
    exit(1)

soup = BeautifulSoup(response.content, 'html.parser')

data = [] #class="text left cb text_wrap motion fadeIn visible"
html = soup.find('div', {'class' :'text left cb text_wrap motion fadeIn visible'})


# Not returning correctly.
if html is None:
    print('it is not getting data')
    exit(2)

我应该输入什么来获得那部分?

标签: pythonparsingbeautifulsoup

解决方案


你需要改变这个:

html = soup.find('div', {'class' :'text left cb text_wrap motion fadeIn visible'})

对此:

html = soup.find('div', {'class' :'text left cb text_wrap motion'})

因为如果您检查页面源,该 div 看起来像这样:

<div class="text left cb text_wrap motion" data-animation="fadeIn">

推荐阅读