当前位置: 代码迷 >> python >> 在Python BeautifulSoup中获取与目标的特定链接
  详细解决方案

在Python BeautifulSoup中获取与目标的特定链接

热度:74   发布时间:2023-07-16 10:10:23.0

我正在尝试使用BeautifulSoup使用Python解析HTML源。 我需要获取的是特定链接的href<a>标记)。 我看到的功能是这些链接都在其标签内包含target='testwindow' ,所以也许我会寻找。 我如何获得这些链接?

这是我的测试样本。 需要获取http://example.com:20213/testweb1.2/testapp?WSDL

<td id="link3"><img src="images/spacer.gif" alt="" style="height:1px;" width="0" border="0"><a href="http://example.com:20213/testweb1.2/testapp?WSDL">?HELLO</a></td>
<td id="link4"><img src="images/spacer.gif" alt="" style="height:1px;" width="0" border="0"><a href="http://example.com:20213/testweb1.2/testapp?WSDL" target="testwindow">?WSDL</a></td>

您可以使用BeautifulSoup.find

from bs4 import BeautifulSoup as soup
content = '<td id="link4"><img src="images/spacer.gif" alt="" style="height:1px;" width="0" border="0"><a href="http://example.com:20213/testweb1.2/testapp?WSDL" target="testwindow">?WSDL</a></td>'
d = soup(content, 'html.parser').find('a', {'target':'testwindow'})['href']

输出:

'http://example.com:20213/testweb1.2/testapp?WSDL'