python - 如何使用 Python 和 BS4 读取相邻 html 元素的内容?

标签 python html beautifulsoup html-parsing web-crawler

使用Python和BeautifulSoup4,在页面源代码中找到特定链接后如何读取下一个html元素。例如,在这个页面源代码片段中:

<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 下载)。

最佳答案

只需找到资源中的 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

关于python - 如何使用 Python 和 BS4 读取相邻 html 元素的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27220893/

相关文章:

javascript - HTML linter 中的 Microsoft VS Code 和 Angular 2 标签

python - python中href url中的正则表达式编号

python - 安装 scrapy 清理失败

python - 如何在 ubuntu 15.04 中安装 poppler?

python - 使用 scipy 进行曲线拟合 - 我收到类型错误

javascript - 如何在圆形 Canvas 上添加线条

python - 确定何时没有数据库行与 Python mysql.connector 匹配

javascript - 将变量添加到 d3/javascript 对象工具提示的 href 链接

python - 在 Python 中抓取 onclick 表

python - 仅将唯一项附加到 python 列表?