【问题标题】:How do you read contents of adjacent html element using Python and BS4?您如何使用 Python 和 BS4 读取相邻 html 元素的内容?
【发布时间】:2015-01-29 00:22:42
【问题描述】:

使用 Python 和 BeautifulSoup4,如何在页面源中找到特定链接后读取下一个 html 元素。比如在这个页面源码的sn-p中:

<a class="" onclick="" href="http://moodle.example.com/mod/resource/view.php?id=16952"><img src="http://moodle.example.com/theme/image.php/afterburner/core/1410701261/f/document-24" class="iconlarge activityicon" alt=" " role="presentation" /><span class="instancename">100 Days of English<span class="accesshide " > File</span></span></a>

我能够提取到资源的链接,但需要文件类型,该文件类型可以从示例中的“src”链接“document-24”末尾紧跟的“img”标签中识别这里。 (pdf-24、powerpoint-24 是其他文件类型指标的示例)

当前代码:

for resource in soup.find_all('a'):
    if '/mod/resource/view.php?id=' in resource.get('href'):
        file_list.append(str(resource.get('href')))

获取所有资源的链接(然后我使用 Mechanize 下载)。

【问题讨论】:

    标签: python html beautifulsoup html-parsing web-crawler


    【解决方案1】:

    只要在资源中找到img标签,将src属性值除以/,得到最后一个元素:

    from bs4 import BeautifulSoup
    
    data = """
    <a class="" onclick="" href="http://moodle.example.com/mod/resource/view.php?id=16952">
        <img src="http://moodle.example.com/theme/image.php/afterburner/core/1410701261/f/document-24" class="iconlarge activityicon" alt=" " role="presentation" />
        <span class="instancename">100 Days of English<span class="accesshide " > File</span></span>
    </a>
    """
    
    soup = BeautifulSoup(data)
    for resource in soup.find_all('a'):
        if '/mod/resource/view.php?id=' in resource.get('href'):
            src = resource.img.get('src')
            print src.split('/')[-1]
    

    打印document-24

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 2021-11-15
      相关资源
      最近更新 更多