将链接放入带圆括号的BeautifulSoup中


BeautifulSoup的get_text((函数只记录HTML网页的文本信息。但是,我希望我的程序在返回实际文本后直接返回括号中标记的href链接。

换句话说,使用get_text((只会返回"17.602";在以下HTML上:

<a class="xref fm:ParaNumOnly" href="17.602.html#FAR_17_602">17.602</a>

然而,我希望我的程序返回";17.602(17.602.html#FAR_17_602(";。我该怎么做?

编辑:如果你需要打印其他标签的文本,比如:

<p> Sample text.
<a class="xref fm:ParaNumOnly" href="17.602.html#FAR_17_602">17.602</a>
Sample closing text.
</p>

换句话说,你将如何编写一个打印的程序

Sample text. 17.602 (17.602.html#FAR_17_602) Sample closing text.

您可以使用f-string格式化输出。

使用.text访问标记的文本,然后访问href属性。

from bs4 import BeautifulSoup
html = """
<a class="xref fm:ParaNumOnly" href="17.602.html#FAR_17_602">17.602</a>
"""
soup = BeautifulSoup(html, "html.parser")
a_tag = soup.find("a")
print(f"{a_tag.text} ({a_tag['href']})")

输出:

17.602 (17.602.html#FAR_17_602)

编辑:您可以使用.next_sibling.previous_sibling

print(f"{a_tag.previous_sibling.strip()} {a_tag.text} ({a_tag['href']}) {a_tag.next_sibling.strip()}")

输出:

Sample text. 17.602 (17.602.html#FAR_17_602) Sample closing text.

最新更新