【问题标题】:How can I merge two beautiful soup tags?如何合并两个漂亮的汤标签?
【发布时间】:2016-06-02 13:53:29
【问题描述】:

我正在提取页面正文中出现的所有<ul> 标记,并连接紧接在它们之前的<p> 标记。

text = BeautifulSoup(requests.get('http://www.getspokal.com/how-to-create-content-based-on-your-customers-pain-points/', timeout=7.00).text)

我用美汤的函数来拉取合适的标签:

def funct(tag):
        return tag.name == 'ul' and not tag.attrs and not tag.li.attrs and not tag.a
ul_tags = text.find_all(funct)

这会拉出三个<ul> 标签。现在找到每个<ul>标签之前的<p>标签并连接:

combined = [(ul.find_previous("p") + ul) for ul in ul_tags]

这会产生一个错误

TypeError: unsupported operand type(s) for +: 'Tag' and 'Tag'

其中一个结果应该是这样的:

<p>For example, if you’re in the pet food industry, you might ask your existing customers:</p<ul><li>What challenges do you face on a regular basis with regards your pets?</li><li>Are there any underlying health issues that your pets have that causes you concern?</li><li>What is your biggest struggle when choosing appropriate food for your pet? </li></ul>

列表理解哪里出了问题?

【问题讨论】:

    标签: python tags beautifulsoup


    【解决方案1】:

    您应该将列表理解更改为:

    combined = [(str(ul.find_previous("p")) + str(ul)) for ul in ul_tags]
    

    问题是ul不是字符串,实际上是bs4.element.Tag,所以必须先转换一下。

    【讨论】:

      猜你喜欢
      • 2012-12-27
      • 2015-05-03
      • 1970-01-01
      • 2018-11-02
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      相关资源
      最近更新 更多