尝试使用beauthulsoup从本地文件收集数据

2024-10-03 11:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想运行一个python脚本来解析html文件,并收集一个带有target="_blank"属性的所有链接的列表。在

我试过以下方法,但没有从bs4中得到任何东西。SoupStrainer在文件中说,它将采取与findAll等相同的方式,这个工作吗?我错过了一些愚蠢的错误吗?在

import os
import sys

from bs4 import BeautifulSoup, SoupStrainer
from unipath import Path

def main():

    ROOT = Path(os.path.realpath(__file__)).ancestor(3)
    src = ROOT.child("src")
    templatedir = src.child("templates")

    for (dirpath, dirs, files) in os.walk(templatedir):
        for path in (Path(dirpath, f) for f in files):
            if path.endswith(".html"):
                for link in BeautifulSoup(path, parse_only=SoupStrainer(target="_blank")):
                    print link

if __name__ == "__main__":
    sys.exit(main())

Tags: 文件pathinimportsrctargetforos
2条回答

用法BeautifulSoup是可以的,但是您应该传入html字符串,而不仅仅是html文件的路径。BeautifulSoup接受html字符串作为参数,而不是文件路径。它不会打开它,然后自动读取内容。你应该自己做。如果你通过a.html,汤将是{}。这不是文件的内容。当然没有联系。您应该使用BeautifulSoup(open(path).read(), ...)。在

编辑:
它还接受文件描述符。BeautifulSoup(open(path), ...)就够了。在

我想你需要这样的东西

if path.endswith(".html"):
    htmlfile = open(dirpath)
    for link in BeautifulSoup(htmlfile,parse_only=SoupStrainer(target="_blank")):
        print link

相关问题 更多 >