使用BeautifulSoup在HTML中选择div块

2024-04-19 00:08:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用一个网站上的一些html,使用beautifuldshop解析几个div块。但是,我无法确定应该使用哪个函数来选择这些div块。我试过以下方法:

import urllib2
from bs4 import BeautifulSoup

def getData():

    html = urllib2.urlopen("http://www.racingpost.com/horses2/results/home.sd?r_date=2013-09-22", timeout=10).read().decode('UTF-8')

    soup = BeautifulSoup(html)

    print(soup.title)
    print(soup.find_all('<div class="crBlock ">'))

getData()

我希望能够在<div class="crBlock ">和它的正确结尾</div>之间选择所有内容。(显然还有其他div标记,但我想一直选择这个块,直到它代表html这一节的结尾。)


Tags: 方法函数importdiv网站html结尾urllib2
1条回答
网友
1楼 · 发布于 2024-04-19 00:08:45

正确的用法是:

soup.find_all('div', class_="crBlock ")

默认情况下,“靓汤”将返回整个标记,包括内容。如果你把它存储在一个变量中,你可以做任何你想做的事情。如果只查找一个div,也可以使用find()。例如:

div = soup.find('div', class_="crBlock ")
print(div.find_all(text='foobar'))

查看documentation page以获取有关您可以使用的所有筛选器的详细信息。

相关问题 更多 >