如何在Python中使用beauthoulsoup查找链接和修改Html

2024-10-04 09:26:38 发布

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

从如下Html输入开始:

<p>
<a href="http://www.foo.com">this if foo</a>
<a href="http://www.bar.com">this if bar</a>
</p>

使用BeautifulGroup,我想将此Html更改为:

^{pr2}$

将已解析的链接保存到字典中,结果如下:

links_dict = {"1":"http://www.foo.com","2":"http://www.bar.com"}

使用BeautifulSoup可以做到吗?有什么有效的选择吗?在


Tags: comhttpif字典foo链接htmlwww
1条回答
网友
1楼 · 发布于 2024-10-04 09:26:38

这在靓汤里应该很容易。在

比如:

from BeautifulSoup import BeautifulSoup
from BeautifulSoup import Tag

count = 1
links_dict = {}
soup = BeautifulSoup(text)
for link_tag in soup.findAll('a'):
  if link_tag['href'] and len(link_tag['href']) > 0:
    links_dict[count]  = link_tag['href']  
    newTag = Tag(soup, "a", link_tag.attrs)
    newTag.insert(0, ''.join([''.join(link_tag.contents), "[%s]" % str(count)]))
    link_tag.replaceWith(newTag)
    count += 1

对文本执行此操作的结果:

^{2}$

对于这个解决方案,我能预见的唯一问题是,如果链接文本包含子标签,那么您将无法执行''.join(link_tag.contents);而需要导航到最右边的文本元素。在

相关问题 更多 >