簡體   English   中英

Python:Beautiful湯中的find_all不會返回預期的結果

[英]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是空的。 難道我做錯了什么?

作為參考,我要在此處抓取的頁面是這里

確保您使用的是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM