【问题标题】:Beautiful soup div with class and id both美丽的汤 div 与类和 id 两者
【发布时间】:2015-03-20 08:42:36
【问题描述】:

我是初学者,想问如何使用美丽的汤从以下类型的代码中提取数据:

<div class="about-book" id="aboutbook">
Blah blah blah
</div>

当“about-book”具有不同的 id 和“aboutbook”具有不同的类名时如何获得“Blah blah blah”。我想要的是类名和 id 的组合。

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup


    【解决方案1】:
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup("""<div class="about-book" id="aboutbook">
    Blah blah blah
    </div>""")
    
    print([x.text for x in soup.find_all("div",attrs={"class":"about-book","id":"aboutbook"})])
    [u'\nBlah blah blah\n']
    

    如果只有一个:

      print(soup.find("div",attrs={"class":"about-book","id":"aboutbook"}).text)
    

    【讨论】:

    • 回溯(最近一次调用最后):文件“bigpm.py”,第 31 行,在 中 print([ x.text for x in soup.find_all("div",attrs={ "class":"about-book"}) if x["id"] == "aboutbook"]) 文件“C:\Python27\lib\site-packages\bs4\element.py”,第 905 行,在 getitem return self.attrs[key] KeyError: 'id'
    • 应该是.get
    • 您也可以使用attrs={'id': 'aboutbook', 'class': 'about-book'} 并为自己保存一个if 声明...
    【解决方案2】:

    试试"div#aboutbook.about-book"

    使用beautifulsoup,你可以这样写:

    soup = BeautifulSoup(html) soup.find_all("div", class_="about-book", id="aboutbook")
    

    【讨论】:

    • 你能举例说明如何在beautifulsoup bcz中写同样的东西,它似乎不起作用
    • 基于文档:soup = BeautifulSoup(html) soup.find_all("div", class_="about-book", id="aboutbook")
    猜你喜欢
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 2021-01-15
    • 1970-01-01
    相关资源
    最近更新 更多