Python: find_all 中的 Beautiful soup 没有 return 所期望的

Python: find_all in Beautiful soup does not return what is expected

我有一个 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.

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

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

不是from BeautifulSoup import BeautifulSoup

尝试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()

尝试以下操作:

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