文件对象美丽的汤

时间:2014-01-22 16:52:10

标签: python file beautifulsoup

这两者有什么区别?

data = open(fil_name, 'r').read()
datap = BeautifulSoup(data,'lxml')

with open(fil_name, 'r') as openfh:
    soup = BeautifSoup(openfh, 'lxml')

哪个相关?

1 个答案:

答案 0 :(得分:2)

是的,您可以将打开的文件句柄传递给BeautifulSoup

with open(fil_name, 'r') as openfh:
    soup = BeautifSoup(openfh, 'lxml')

另一方面,你的代码传入一个字符串;字符串来自何处并不重要。您的代码从文件中读取它,但它可以很容易地从网络连接中读取(例如,从URL加载)。

请参阅Making the soup documentation

  

要解析文档,请将其传递给BeautifulSoup构造函数。您   可以传入一个字符串或一个打开的文件句柄:

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("index.html"))

soup = BeautifulSoup("<html>data</html>")
相关问题