代码拉取完成,页面将自动刷新
import html_downloader
import html_outputer
import html_parser
import url_manager
class SpiderMain(object):
def __init__(self):
self.urls = url_manager.UrlManager()
self.downloader = html_downloader.HtmlDownloader()
self.parser = html_parser.HtmlParser()
self.outputer = html_outputer.HtmlOutputer()
def craw(self, root_url):
count = 1 # 爬取第几个页面
self.urls.add_new_url(root_url)
while self.urls.has_new_url():
try: # 处理有些页面链接失效的问题,此时抛出异常
new_url = self.urls.get_new_url()
print('craw %d: %s' % (count, new_url))
html_cont = self.downloader.download(new_url)
new_urls, new_data = self.parser.parse(new_url, html_cont)
self.urls.add_new_urls(new_urls)
self.outputer.collect_data(new_data)
if count == 1000: # 只爬取1000个页面
break
count = count + 1
except Exception as e:
print(e)
print('Craw failed!')
self.outputer.output_html()
if __name__ == "__main__":
root_url = "https://baike.baidu.com/item/Python/407313"
obj_spider = SpiderMain()
obj_spider.craw(root_url)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。