使用python脚本将抓取的数据写入文本文件



我是数据抓取的新手。这是我用python编写的第一个程序来抓取数据并将其存储到文本文件中。我编写了以下代码来抓取数据。

from bs4 import BeautifulSoup
import urllib2
text_file = open("scrape.txt","w") 
url = urllib2.urlopen("http://ga.healthinspections.us/georgia/search.cfm?1=1&f=s&r=name&s=&inspectionType=&sd=04/24/2016&ed=05/24/2016&useDate=NO&county=Appling&")
content = url.read()
soup = BeautifulSoup(content, "html.parser")
type = soup.find('span',attrs={"style":"display:inline-block; font-  size:10pt;"}).findAll()
for found in type:
  text_file.write(found)

但是我使用命令提示符运行此程序,它向我显示以下错误。

c:PyProjScraping>python sample1.py
Traceback (most recent call last):
File "sample1.py", line 9, in <module>
text_file.write(found)
TypeError: expected a string or other character buffer object

我在这里错过了什么,或者有什么我没有添加的。谢谢。

您需要检查type是否None,即soup.find实际上没有找到您搜索的内容。

另外,不要使用名称type,它是一个内置的。

find ,很像find_all返回一个/一个Tag对象的列表。如果在Tag上调用 print,则会看到字符串表示形式。这种自动性不会在file.write上调用。你必须决定要写found的属性。

最新更新