【问题标题】:Get specific links with target in Python BeautifulSoup在 Python BeautifulSoup 中获取与目标的特定链接
【发布时间】:2019-03-10 09:56:48
【问题描述】:

我正在尝试使用 BeautifulSoup 解析 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>

【问题讨论】:

    标签: python html beautifulsoup html-parsing string-parsing


    【解决方案1】:

    你可以使用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'
    

    【讨论】:

    • 不,这会给我所有的链接。我只需要target='testwindow'
    • 太棒了。如果我们有更多这些标签怎么办?也许使用find_all?你能编辑你的答案吗?
    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2017-08-04
    • 1970-01-01
    相关资源
    最近更新 更多