gpt4 book ai didi

python - python 中的匹配字符串模式

转载 作者:太空宇宙 更新时间:2023-11-03 19:09:38 31 4
gpt4 key购买 nike

我有一个可以包含链接的字符串:

<a href="http://site1.com/">Hello</a> <a href="http://site2.com/">Hello2</a>
<a href="http://site3.com">Hello3</a> ...

如何提取所有 html 标签“Hello”、“Hello2”、“Hello3”... 的文本(而不是链接)?我正在考虑一个应该包含所有文本的列表。

最佳答案

使用lxml :

import lxml.html as LH

content = '''
<a href="http://site1.com/">Hello</a> <a href="http://site2.com/">Hello2</a>
<a href="http://site3.com">Hello3</a>
<a href="/">go <b>home</b>, dude!</a>
'''

doc = LH.fromstring(content)
texts = [elt.text_content() for elt in doc.xpath('//a')]
print(texts)

产量

['Hello', 'Hello2', 'Hello3', 'go home, dude!']

关于python - python 中的匹配字符串模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13425580/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com