我正在开发一个自动化程序,使用 BeautifulSoup 和 Python 3 来识别网站 Logo 。第一步,我正在寻找图像名称中包含“ Logo ”一词的图像。它实际上工作得很好。但是,我想将其扩展为可能包含术语图像或包含在带有表示 Logo 的类/id/属性的链接中的图像,或者甚至更深地埋在包含 ' 类的 div 中的链接中标识'。例如:
<div id="logo">
<a href="http://www.mexgrocer.com/">
<img src="http://ep.yimg.com/ca/I/mex-grocer_2269_22595" width="122" height="72" border="0" hspace="0" vspace="0" alt="Mexican Food">
</a>
</div>
我现在的代码是:
img = soup.find("img",src=re.compile(r'logo',re.I))
如何扩展它以搜索所有父标签属性?
最佳答案
使用find_all
查找整个文档中的所有特定标签。你可以这样尝试
from bs4 import Beautifulsoup
import urllib2
soup = BeautifulSoup(urllib2.urlopen('your_url').read())
for x in soup.find_all(id='logo'):
try:
if x.name == 'img':
print x['src']
except:pass
如果你想搜索类(class),只需使用class='logo'
关于python - BeautifulSoup - 寻找标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26691799/