如何使用单个BeautifulSoup对象打印子标记内的文本和孙元素的href?

时间:2014-10-11 23:12:21

标签: python html html-parsing beautifulsoup

我有一个包含多个div.inventory兄弟姐妹的文档。

<div class="inventory">
    <span class="item-number">123</span>
    <span class="cost">
           <a href="http://linktoitem" class="price">$1.23</a>
    </span>
</div>

我想迭代它们来打印项目编号和项目链接。

123 http://linktoitem
456 http://linktoitem2
789 http://linktoitem3

如何在选择div.inventory元素后解析这两个值?

import requests
from bs4 import BeautifulSoup
htmlSource = requests.get(url).text
soup = BeautifulSoup(htmlSource)
matches = soup.select('div.inventory')
for match in matches:
    #prints 123
    #prints http://linktoitem

另外 - select函数和find*函数之间有什么区别?

1 个答案:

答案 0 :(得分:4)

您可以依赖class属性

使用find()找到这两个项目
soup = BeautifulSoup(data)
for inventory in soup.select('div.inventory'):
    number = inventory.find('span', class_='item-number').text
    link = inventory.find('span', class_='cost').a.get('href')
    print number, link

示例:

from bs4 import BeautifulSoup

data = """
<body>
    <div class="inventory">
        <span class="item-number">123</span>
        <span class="cost">
               <a href="http://linktoitem" class="price">$1.23</a>
        </span>
    </div>
    <div class="inventory">
        <span class="item-number">456</span>
        <span class="cost">
               <a href="http://linktoitem2" class="price">$1.23</a>
        </span>
    </div>
    <div class="inventory">
        <span class="item-number">789</span>
        <span class="cost">
               <a href="http://linktoitem3" class="price">$1.23</a>
        </span>
    </div>
</body>
"""

soup = BeautifulSoup(data)
for inventory in soup.select('div.inventory'):
    number = inventory.find('span', class_='item-number').text
    link = inventory.find('span', class_='cost').a.get('href')
    print number, link

打印:

123 http://linktoitem
456 http://linktoitem2
789 http://linktoitem3

请注意使用select() - 此方法允许使用CSS Selectors在页面上进行搜索。另请注意使用class_ argument - 下划线非常重要,因为class是Python中的反向关键字。