以下是十分简单的python写的爬虫小脚本。
import os,re
import urlparse,urllib,urllib2
import hashlib,Queue
class Request(object):
def __init__(self):
self.url= ''
self.error_url = []
self.undownload_url = []
self.downloaded_url = []
self.headers={'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) \
Gecko/20091201 Firefox/3.5.6',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}
def read_url_from_file(self):
urls = []
try:
r = open('urls.txt','r')
urls = r.readlines()
r.close()
except IOError:
url = raw_input("no file urls.txt,please input a url >>> ")
if not url.lower().startswith('http://'):
url = 'http://'+url
urls.append(url)
return urls
def is_download_url(self):
return self.url in self.downloaded_url
def get(self):
ok = False
req = urllib2.Request(self.url,None,self.headers)
for i in range(3):
temp = urllib2.urlopen(req)
if temp.getcode()==200:
if 'content-type' in temp.headers.keys():
content_type = temp.headers.get('content-type')
if 'text' in content_type:
return temp.read()
else:
return temp.read()
return ''
def find_links(self):
com = re.compile(r"""<a[^>]*?href\s*=\s*['"]?([^'"\s>]{1,500})['">\s]""",re.I|re.M|re.S)
links = com.findall(self.content)
links = set(links)
links = list(links)
full_links = [urlparse.urljoin(self.url,x) for x in links]
for i in full_links:
if i not in self.undownload_url and i not in self.downloaded_url:
self.undownload_url.append(i)
def save_page(self,page_source,filename):
dirname = filename.split('/')[0]
if not os.path.isdir(dirname):
os.mkdir(dirname)
w = open(filename,'w')
w.write(page_source)
w.close()
def save_result(self,urls,filename):
w = open(filename,'w')
w.write('\n'.join(urls))
w.close()
def run(self):
self.page = 0
self.ldir = 0
self.num_per_dir = 100
self.undownload_url = self.read_url_from_file()
self.url_to_path = {}
try:
while self.undownload_url:
self.url = self.undownload_url.pop(0)
self.url = self.url.replace('\n','')
order = self.page+self.ldir*self.num_per_dir
print (" %4d download... %s " % (order,self.url) )
self.content = self.get()
self.downloaded_url.append(self.url)
if self.content:
self.find_links()
filename = str(self.ldir)+'/'+str(self.page)
self.save_page(self.content,filename)
self.url_to_path[str(order)] = self.url
self.page += 1
if self.page >= self.num_per_dir:
self.page -= self.num_per_dir
self.ldir += 1
else:
self.error_url.append(self.url)
print ("finished !")
except:
print ("save downloaded urls into downloaded file")
self.save_result(self.downloaded_url,'downloaded')
print ("save error urls into error file")
self.save_result(self.undownload_url,'undownload')
print ("save url to file dictonary into url_to_file")
self.save_result([x+'\t'+self.url_to_path[x] for x in self.url_to_path.keys()],'url_to_file')
print ("total try to download %d urls" % order)
aa = Request()
aa.run()
分享到:
相关推荐
crawlerforSinaweibo_爬虫python_webcrawler_python_weibo_python爬虫_源码
使用python实现多机并行爬取网页内容。
可以爬取指定微博的爬虫,基于Python语言
由于python更新,有些API用法有变,原程序已经不能在新版本中正常运行了。经过本人改进测试,此crawler项目能正常运行。 测试平台: win7 python3.7
Packt.Python.Web.Scraping.2nd.Edition.2017.5 英文版 python爬虫技术
# Python_Crawler_Qichacha 基于Python的企查查爬虫,爬取完整的公司数据 -------- 该资源内项目源码是个人的毕设,代码都测试ok,都是运行成功后才上传资源,答辩评审平均分达到96分,放心下载使用! <项目介绍> 1...
weibo_crawler-master-pythonpython源码python源码
python库。 资源全名:spidy_web_crawler-1.6.0-py3-none-any.whl
python 编写的DHT Crawler 网络爬虫,抓取DHT网络的磁力链接。 文件 collector.py dht网络爬虫脚本 抓取dht网络的磁力链接,使用 libtorrent 的python绑定库开发。 collectord.py dht爬虫服务监控程序 启动并监控...
用python实现的视频采集,附带国内几个知名视频站点的相关信息
网页抓取工具python 用于自动下载字体文件的python网络爬虫网站搜寻器,可使用BeautifulSoup和urllib下载所有可用的字体(当前为1100种字体)。 可以轻松地对其进行修改以爬网另一个网站。 脚步 : 遍历目录页面以...
jingdong_crawler-master_python爬虫商城_爬虫python_python_商城_crawls_源码.zip
网络各类型网页爬取数据教程,以及源代码,Python格式
python多线程爬虫爬取电影天堂资源,实测效果好
cra草Web Crawler在python 3.x上使用Scrapy包如何安装软件包? python3 -m pip install Scrapy 如何创建项目? 在终端或CMD或Powershell上运行移到文件夹cd FolderName 创建Scrapy项目scrapy startproject ...
python爬虫日常小练习,小项目-python_crawler
python爬虫项目集合-crawler
weibo_crawler-master-python.rar Python爬虫入门需要掌握Python基础语法、网络请求和数据抓取、解析HTML和XML、处理HTTP响应、数据存储、使用代理和反爬策略、并发和多线程等技术,并遵守相关法律和道德规范。