我有一个包含多个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*
函数之间有什么区别?
答案 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中的反向关键字。