python - 如何合并两个漂亮的汤标签?

标签 python tags beautifulsoup

我正在拉所有 <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>标签。现在找到 <p>紧接在这些 <ul> 之前的标签标记和连接:

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>

列表理解哪里出错了?

最佳答案

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

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

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

关于python - 如何合并两个漂亮的汤标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35531608/

相关文章:

python - int()参数必须是字符串,类似字节的对象或数字,而不是 'NoneType'

css - 在 JSX 中映射数据时无法显示唯一的 react-tag-input 标签

Python NLTK Brill Tagger 没有 SymmetricProximateTokensTemplate、ProximateTokensTemplate、ProximateTagsRule、ProximateWordsRule

Python:从标准输入读取gzip

javascript - Extjs tagfield 在输入框中保存值

html - 为什么 HTML 中不推荐使用 <center> 标签?

python - 如何使用 BeautifulSoup4 只获取 "href"?

python - HTTP 错误 404 : Not Found - BeautifulSoup and Python

javascript - Python3 - 我不想用 BeautifulSoup 打印 Javascript 代码

python - 如何按键值正确排序字典?