使用BeautifulSoup selector获取重复标签全部值仅返回首个结果怎么办
问题原因
select_one() 和 find() 方法本身的设计就是仅返回匹配规则的第一个元素,所以你只会拿到第一个结果,这是正常现象。
解决方案
要获取所有匹配的元素,替换为对应返回全部结果的方法即可:select() 对应 select_one(),find_all() 对应 find()。
方法1:使用select()实现
import requests from bs4 import BeautifulSoup url = 'https://findthatlocation.com/film-title/a-knights-tale' # 原代码中的url[1]属于笔误,直接传入完整url即可 r = requests.get(url) soup = BeautifulSoup(r.content, 'lxml') # 遍历所有匹配的标签提取内容 street = [list(item.stripped_strings)[0] for item in soup.select("div[style='color: #999; font-size: 12px; margin-bottom: 5px;']")] print(street)
输出结果:
['Prague,', 'Prague Castle, Prague']
方法2:使用find_all()实现
st_list = soup.find_all('div', {'style':'color: #999; font-size: 12px; margin-bottom: 5px;'}) st_result = [item.text.strip() for item in st_list] print(st_result)
补充提示
依赖style属性作为选择器的稳定性很低,一旦站点调整样式属性值,代码就会失效,建议优先使用固定的class、id或者标签层级关系作为定位规则,兼容性会更强。
内容的提问来源于stack exchange,提问作者Stackcans
相关产品推荐
相关产品推荐

