BeautifulSoup - 为什么打印文件路径而不是内容

时间:2013-10-17 14:09:47

标签: python html beautifulsoup filepath

我想了解BeautifulSoup的工作原理。请注意,我对Python很陌生,所以我可能会遗漏一些东西。

我打开一个Python终端并写下:

from bs4 import BeautifulSoup
import re
ytchannel = '/home/XXX/Documents/test2'
soup = BeautifulSoup(ytchannel)
print(soup.prettify())

这就是我得到的:

<html>
 <body>
  <p>
   /home/XXX/Documents/test2
  </p>
 </body>
</html>

为什么呢?对我来说完全是无稽之谈。我只想要test2的内容。 我正在写下BeautifulSoup网站上写的内容。

1 个答案:

答案 0 :(得分:1)

您将字符串传递给BeautifulSoup();确定它是文件名,但BeautifulSoup()不会为您打开文件名。它仅对字符串或打开的文件对象进行操作。

首先打开文件;如果你传递了文件对象,BeautifulSoup()将读取文件对象:

with open(ytchannel) as infile:
    soup = BeautifulSoup(infile)

请参阅Making the soup