Python:美丽汤中的find_all不会返回预期的内容

时间:2015-10-15 04:55:47

标签: python python-2.7 beautifulsoup findall

我有一个像这样的HTML:

        <ul class='Whs-nw M-0 items'>
            <li>
                <a href='/news/stocks-hold-slight-gains-amid-140642829.html' class='D-b Fz-s Fw-400' data-ylk='rspns:nav;t3:sub0;elm:hdln;elmt:ct;itc:0;pkgt:15;g:e3b49674-fd8a-3acb-9395-4ac0811af672;ct:1;cpos:2;'>
                <div class='P-0 Whs-n'>
                    <div class='M-0 Pt-2 Ov-h'>


                    <p class='M-0 D-i'>Dow closes down more than 150 as Wal-Mart, Boeing weigh</p>
                    </div>
                </div>
                </a>
            </li>
            ...
        </ul>

我正在尝试使用Beautifulsoup来提取/news/stocks-hold-slight-gains-amid-140642829.html,我这样做:

soup = BeautifulSoup(html)
tmp= soup.find_all('ul', attrs={'class' : 'Whs-nw M-0 items'})

但是当我看到它时tmp是空的。 我做错了吗?

作为参考,我试图抓取的页面是 HERE

3 个答案:

答案 0 :(得分:0)

确保您正在使用bs4,当我使用旧版本时,它会失败,但使用新版本时它会正常工作。所以,你应该这样做:

from bs4 import BeautifulSoup
...
soup = BeautifulSoup(html)
tmp= soup.find_all('ul', attrs={'class' : 'Whs-nw M-0 items'})

不是from BeautifulSoup import BeautifulSoup

答案 1 :(得分:0)

尝试tmp= soup.findAll('ul', {'class' : 'Whs-nw M-0 items'})tmp= soup.find_all('ul', attrs={'class' : 'Whs-nw M-0 items'})

工作代码 -

import urllib2
from bs4 import BeautifulSoup
response = urllib2.urlopen('http://finance.yahoo.com/')
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
tmp= soup.findAll('ul', {'class' : 'Whs-nw M-0 items'})
for i in tmp:
    print i.get_text()

答案 2 :(得分:0)

尝试以下方法:

temp = soup.find('ul', attrs={'class': 'Whs-nw M-0 items'}).find('a')['href']

或者你可以这样做:

soup = BeautifulSoup(html)

temp = soup.find('a', {'class': 'D-b Fz-s Fw-400'})['href']

print temp

输出: /news/stocks-hold-slight-gains-amid-140642829.html