python从div块获取数据

时间:2016-08-05 13:29:51

标签: python beautifulsoup

我正在尝试使用Beautiful Soup解析div块

哪个是

<div class="same-height-left" style="height: 20px;"><span class="value-frame">&nbsp;whatever</span></div>

我想得到[我期待的]:

whatever<span class="value-frame">&nbsp;whatever</span>

我试过

response = requests.get('http://example.com')
response.raise_for_status()
soup = bs4.BeautifulSoup(response.text)

div = soup.find('div', class_="same-height-left")

结果

  

soup = bs4.BeautifulSoup(response.text)

div = soup.find_all('div', class_="same-height-left")

结果

  

[]

1 个答案:

答案 0 :(得分:2)

这个怎么样:

from bs4 import BeautifulSoup

html = """<div class="same-height-left" style="height: 20px;"><span class="value-frame">&nbsp;whatever</span></div>"""

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

method1 = soup.find('div').text
method2 = soup.find('div').find('span').text
method3 = soup.find('span', class_='value-frame').text

print 'Result of method 1:' + method1  # prints " whatever"
print 'Result of method 2:' + method2  # prints " whatever"
print 'Result of method 3:' + method3  # prints " whatever"