【问题标题】:How to remove html tags from strings in Python using BeautifulSoup如何使用 BeautifulSoup 从 Python 中的字符串中删除 html 标签
【发布时间】:2014-03-11 00:14:36
【问题描述】:

这里是编程新手 :)

我想使用 BeautifulSoup 打印网站上的价格。这是我的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


from bs4 import BeautifulSoup, SoupStrainer
from urllib2 import urlopen

url = "Some retailer's url"
html = urlopen(url).read()
product = SoupStrainer('span',{'style': 'color:red;'})
soup = BeautifulSoup(html, parse_only=product)
print soup.prettify()

它按以下顺序打印价格:

<span style="color:red;">
 180
</span>
<span style="color:red;">
 1250
</span>
<span style="color:red;">
 380
</span>

我尝试了print soup.text.strip(),但它返回了1801250380

请帮我打印每行的价格:)

非常感谢!

【问题讨论】:

    标签: python-2.7 beautifulsoup


    【解决方案1】:
    >>> print "\n".join([p.get_text(strip=True) for p in soup.find_all(product)])
    180
    1250
    380
    

    【讨论】:

      【解决方案2】:

      这将为您提供转换为整数的字符串列表:

      >>> [int(span.text) for span in soup.find_all('span')]
      [180, 1250, 380]
      

      【讨论】:

      • 如果标记从span 更改为div,这将停止工作。
      • 所以你是说如果代码结构发生变化,网页抓取代码需要更新?这应该是不言而喻的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-14
      • 2015-03-24
      • 2012-01-31
      • 2021-06-21
      • 1970-01-01
      • 2013-02-24
      相关资源
      最近更新 更多