【问题标题】:Python: find_all in Beautiful soup does not return what is expectedPython:Beautiful soup 中的 find_all 未返回预期结果
【发布时间】:2016-01-13 10:00:03
【问题描述】:

我有一个这样的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

【问题讨论】:

  • 你使用什么库来获取内容请求,selenium httplib 等?

标签: python python-2.7 beautifulsoup findall


【解决方案1】:

尝试以下方法:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我发现您的代码与findAllfind_all 一起使用。但是,嘿,它正在工作! :)
    【解决方案3】:

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

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

    不是from BeautifulSoup import BeautifulSoup

    【讨论】:

    • 我用的是bs4,能不能把我提到的部分提取出来?
    • 是的,我将其转换为字符串,在 bs4 中可以正常工作。
    • 你试过了吗?当您执行 Web 请求时,该页面实际上可能不包含您想要的数据。它可以通过 ajax 调用加载。
    • 为什么我认为你使用旧版本是因为它不支持像你正在做的带有空格的子类......
    • 不,我查看了页面源代码,它在那里,所以没有被 Ajax 调用加载。
    猜你喜欢
    • 1970-01-01
    • 2014-11-29
    • 2011-08-09
    • 2010-09-22
    • 2021-05-17
    • 2018-02-19
    • 2018-03-23
    • 2020-03-15
    • 1970-01-01
    相关资源
    最近更新 更多