python/beautifulsoup查找所有具有特定锚文本的

2024-09-27 09:28:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用beautifuldsoup来解析html,并使用一个特定的锚标记来查找所有的ref

<a href="http://example.com">TEXT</a>
<a href="http://example.com/link">TEXT</a>
<a href="http://example.com/page">TEXT</a>

我正在寻找的所有链接都有完全相同的锚文本,在本例中是文本。我不是在找文字,我想用文字找到所有不同的

编辑:

寻找类似于使用类解析链接的内容

<a href="http://example.com" class="visible">TEXT</a>
<a href="http://example.com/link" class="visible">TEXT</a>
<a href="http://example.com/page" class="visible">TEXT</a>

然后使用

findAll('a', 'visible')

除了我正在解析的HTML没有类,但是始终是相同的锚文本


Tags: text标记文本comhttp链接examplehtml
1条回答
网友
1楼 · 发布于 2024-09-27 09:28:39

想要这个吗?

In [39]: from bs4 import BeautifulSoup

In [40]: s = """\
   ....: <a href="http://example.com">TEXT</a>
   ....: <a href="http://example.com/link">TEXT</a>
   ....: <a href="http://example.com/page">TEXT</a>
   ....: <a href="http://dontmatchme.com/page">WRONGTEXT</a>"""

In [41]: soup = BeautifulSoup(s)

In [42]: for link in soup.findAll('a', href=True, text='TEXT'):
   ....:     print link['href']
   ....:
   ....:
http://example.com
http://example.com/link
http://example.com/page

相关问题 更多 >

    热门问题