-1

我想在 ping 它之前从文本文档中删除跨度标签,否则它将失败,但我无法让它删除跨度标签并在没有标签的情况下再次保存文件或将新结果保存到数组中保存.

from bs4 import BeautifulSoup

with open(r'sitelist.txt') as f:
    f = f.read().splitlines()

soup = BeautifulSoup(f,"html.parser")

while len(soup.find_all('span')) > 0:
    soup.span.extract()

f = soup

return f

我试图分解或打开包装,但无法得到我想要的结果。

4

2 回答 2

1

如上所述,您不需要使用readline(),只需read(). 我不确定提取是否有效,是吗?这是我的解决方案,它只是删除了跨度标签(我认为这是您所要求的):

from bs4 import BeautifulSoup

with open('sitelist.txt', 'r') as html:
    soup = BeautifulSoup(myfile,"html.parser")
    for match in soup.findAll('span'): 
        match.unwrap()

with open('sitelist.txt', 'w') as html:
    html.write(str(soup))

我确信有一种方法可以打开文件进行读写,但我只是打开并重新打开了两次文件。

于 2016-01-08T01:18:12.930 回答
0

啊...str.splitlines()返回一个列表,你不能只BeautifulSoup()在列表上使用。相反,只需替换f = f.read().splitlines()f = f.read().

然后,您的代码可以工作,您只需要将输出写入文件,对吗?

from bs4 import BeautifulSoup

with open(r'sitelist.txt') as f:
    f = f.read()

soup = BeautifulSoup(f, "html.parser")

while len(soup.find_all('span')) > 0:
    soup.span.extract()

with open(r'sitelist.txt', 'w') as f:
    f.write(str(soup))
于 2016-01-08T00:58:08.880 回答