繁体   English   中英

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

[英]Write data scraped to text file with python script

我是数据抓取的新手。 这是我用 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:\PyProj\Scraping>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属性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM