用Python的BeautifulSoup4查找所有以字符串开头的标签属性

0 投票
1 回答
763 浏览
提问于 2025-04-18 11:05

我该如何使用beautifulsoup来找到所有属性以某个字符串开头的标签呢?

下面这个方法似乎不太管用 :(

soup.find_all('a', {'href':re.compile('^com')})

1 个回答

2

看起来这个功能是正常的……我觉得你遇到的问题可能是因为你的例子不对。通常,一个 href 标签不会以 com 开头,它们一般是以 httphttps 开头的。

把你的例子放到你自己的问题上运行,结果是正常的:

import requests
from bs4 import BeautifulSoup
import re

html = requests.get("http://stackoverflow.com/questions/24416106/beautifulsoup4-find-all-tags-with-attribute-begins-with-a-string-in-python")
soup = BeautifulSoup(html.text)

http = soup.find('a', {'href':re.compile('^http')})
print http

输出结果是:

<a data-gps-track="site_switcher.click({ item_type:6 })" href="http://chat.stackoverflow.com">chat</a>

如果你把 ^http 换成 ^https,你会得到一个以 https 开头的 a 标签和 href

注意:我为了简单起见使用了 find() 方法。

撰写回答