使用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/