【问题标题】:Python - BeautifulSoup4 decompose() isn't workingPython - BeautifulSoup4 decompose() 不工作
【发布时间】:2014-09-18 06:23:34
【问题描述】:

我正在尝试从此页面获取所有标题的类别。

from bs4 import BeautifulSoup
import urllib2

headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) \
         AppleWebKit/537.36 (KHTML, like Gecko) \
         Ubuntu Chromium/33.0.1750.152 Chrome/33.0.1750.152 Safari/537.36'
}
category_url = ''
html = urllib2.urlopen(urllib2.Request(category_url, None, headers)).read()
page = BeautifulSoup(html)
results = page.find('div', {'class': "results"}).find_all('li')

for res in results:
    category = res.find(attrs={'class': "category"}) or res.find(attrs={'class': "categories"})
    #print category  #till here, I'm getting correct data
    print category.b.decompose() #here is the problem? I should get the div element without <b> tag but it returns None

我收到的是None,而不是更新的 dom。

PS:如果您有任何改进此代码的建议,请告诉我。我很乐意进行更改以获得更好的性能和 Python 代码。

【问题讨论】:

    标签: python python-2.7 python-3.x beautifulsoup lxml


    【解决方案1】:

    Decompose 从树中删除标签,并返回 None,而不是剩余的树。这类似于list.appendlist.sort 的工作方式。 (这些方法也会修改调用者并返回None。)

    for res in results:
        category = res.find(attrs={'class': "category"}) or res.find(attrs={'class': "categories"})
        category.b.decompose()
        print(category)
    

    产生类似的输出

    <div class="categories">
    
    <span class="highlighted">Advertising</span> <span class="highlighted">Agencies</span> </div>
    

    使用 lxml:

    import lxml.html as LH
    import urllib2
    
    category_url = 'http://www.localsearch.ae/en/category/Advertising-Agencies/1013'
    doc = LH.parse(urllib2.urlopen(category_url))    
    for category in doc.xpath(
        '//div[@class="category"]|//div[@class="categories"]'):
        b = category.find('b')
        category.remove(b)
        print(LH.tostring(category))
    

    【讨论】:

    • 谢谢。您是否发现任何需要改进的地方。至于类别,我将or 用于两个不同的类别。有没有更好的方法来做到这一点。
    • 从标签中我看到你有lxml,所以我只会使用XPath(见上文)。
    猜你喜欢
    • 2018-10-04
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 2013-10-25
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    相关资源
    最近更新 更多