【发布时间】:2016-03-21 19:02:11
【问题描述】:
我正在尝试收集有关我所在地区的大量人口普查数据,从一个链接开始以获取正确的代码。最初,我想获取页面的标题并将页面中的数据存储在以标题命名的 txt 文件中。
例如,在这种情况下,Census Block 970900-1-001 in Cortland County, New York 将是 txt 文件的标题。但是,当我尝试使用% variable 方法执行此操作时,它给了我错误Unsupported operand type for %: 'file' and 'unicode'。我理解错误消息 - 我的问题是,我怎样才能实现我想要的功能,或者它甚至可能吗?
到目前为止编写的代码:
from bs4 import BeautifulSoup
from urllib2 import urlopen
links = ['http://www.usa.com/NY0239709001001.html']
def block():
link = links[0]
html = urlopen(link)
soup = BeautifulSoup(html.read(),'lxml')
h1 = soup.find('h1').text
print(h1)
f = open('%s.txt','w') % h1
f.write(h1)
预期输出:
创建一个名为Census Block 970900-1-001 in Cortland County, New York.txt的文件
实际输出:
Unsupported operand type for %: 'file' and 'unicode'
【问题讨论】: