【问题标题】:Parsing out data using Beautifulsoup ignoring part of the tag使用 Beautifulsoup 解析数据,忽略部分标签
【发布时间】:2020-09-19 20:48:01
【问题描述】:

我正在学习 Beautifulsoup……到目前为止,我的代码一直运行良好,直到我找到了这个标签。

oldPrice = soup.find('p', class_='old-price')
print(oldPrice.prettify())

我收到以下回复:

<p class="old-price">
 <span class="price-label">
  Antes:
 </span>
 <span class="price" id="old-price-355952">
  $ 295
 </span>
</p>

我不知道如何找到所有 (id="old-price-355952 ),因为我正在寻找价格 ($ 295) 但忽略了数字,因为它们在每件商品上都会发生变化。

【问题讨论】:

标签: python beautifulsoup


【解决方案1】:

无需使用正则表达式,BeautifulSoup 也支持 CSS 选择器:

txt = '''<p class="old-price">
 <span class="price-label">
  Antes:
 </span>
 <span class="price" id="old-price-355952">
  $ 295
 </span>
</p>'''

soup = BeautifulSoup(txt, 'html.parser')

print(soup.select_one('span[id^="old-price"]').text)

打印:

  $ 295

更多关于CSS selectors这里。


编辑:对于多个选择器:

txt = '''<p class="old-price">
 <span class="price-label">
  Antes:
 </span>
 <span class="price" id="old-price-355952">
  $ 295
 </span>
 <span class="price" id="special-price-45345">
  $ 199
 </span>

</p>'''

soup = BeautifulSoup(txt, 'html.parser')

for price in soup.select('span[id^="old-price"], span[id^="special-price"]'):
    print(price.get_text(strip=True))

打印:

$ 295
$ 199

或者:

for old_price, special_price in zip(soup.select('span[id^="old-price"]'),
                                    soup.select('span[id^="special-price"]')):
    print('Old price = {} Special price = {}'.format(old_price.text.strip(), special_price.text.strip()))

打印:

Old price = $ 295 Special price = $ 199

【讨论】:

  • 谢谢!!..无论如何要做多个选择器??像这样的东西? print(soup.select_one('span[id^="old-price"]', 'span[id^="special-price"]').text)
  • 谢谢!..由于某种原因,最后一个示例不起作用。 @Andrej Kesely
  • 完全没有错误...进程以退出代码 0 结束
  • 我们开始...最后一个 span 不正确...应该是 id=product-price。再次感谢!你拯救了我的一天
【解决方案2】:

嗯..最后我找到了用正则表达式做的方法:

oldPrice = soup.find('span', id=(re.compile("^old-price-")))
print("Old Price -" + oldPrice.text.strip())

哪些输出

TAPABOCAS
Old Price -$ 295
New Price - $ 236

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2023-01-03
    • 2017-09-24
    相关资源
    最近更新 更多