我想运行一个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())
用法}。这不是文件的内容。当然没有联系。您应该使用
BeautifulSoup
是可以的,但是您应该传入html字符串,而不仅仅是html文件的路径。BeautifulSoup
接受html字符串作为参数,而不是文件路径。它不会打开它,然后自动读取内容。你应该自己做。如果你通过a.html
,汤将是{BeautifulSoup(open(path).read(), ...)
。在编辑:
它还接受文件描述符。
BeautifulSoup(open(path), ...)
就够了。在我想你需要这样的东西
相关问题 更多 >
编程相关推荐