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

2024-10-08 19:31:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含几个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>

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

^{pr2}$

在选择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*函数之间有什么区别?在


Tags: 函数importdivhttpprintsrequestsselectclass
1条回答
网友
1楼 · 发布于 2024-10-08 19:31:13

您可以使用依赖于class属性的^{}找到这两个项目:

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

示例:

^{pr2}$

印刷品:

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

注意使用^{}-此方法允许使用CSS Selectors在页面上搜索。还要注意使用^{} argument-下划线很重要,因为class在Python中是一个反向关键字。在

相关问题 更多 >

    热门问题