python - BeautifulSoup - 寻找标志

标签 python python-3.x beautifulsoup

我正在开发一个自动化程序,使用 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/

相关文章:

python - python - 如何对3列求和

python - 如何测试当前目录是否为 $HOME?

Python Key Error 过滤 MySQL

python - 我的错误 : List or tuple literal expected as the second argument to namedtuple()

python - 从特定 channel 抓取 YouTube 视频并进行搜索?

python - 在模板中调用模型函数不起作用

python - 如何在 Windows 7 上获取结构执行 (fab.exe) 的输出?

Python 字符串切片

javascript - 从 HTML <time> 标签中找出准确的时间

Python - 是否有更有效的方法来查找这些参数值?