看了慕课网的一个网络爬虫教程。模仿着写了一个简单的爬取百度百科的例子。
(1)安装Beautifulsoup4
Beautifulsoup是Python的一个网页解析库,使用起来很方便。http://cuiqingcai.com/1319.html这个链接是介绍如何使用。这个库是需要安装的,进入Pthon安装目录下面的Scripts目录,执行pip install beautifulsoup进行安装。
(2)爬虫具体实现
文章图片
爬虫分为5个模块,调度模块、网页下载模块、网页解析模块、URL管理模块、输出模块。
文章图片
【Python爬虫,爬取百度百科词条】URL管理模块,负责保存最新的网页URL,每次取出最新的URL进行爬取。
#coding=utf8
class UrlManager(object):def __init__(self):
self.new_urls = set()
self.old_urls = set()#添加新的url
def _add_new_url(self, url):
if url is None:
return
if url not in self.new_urls and url not in self.old_urls:
self.new_urls.add(url)#批量添加url
def add_new_urls(self,urls):
if urls is None or len(urls) == 0:
returnfor url in urls:
self._add_new_url(url)#是否有新的url
def has_new_url(self):
return len(self.new_urls) != 0#获取新的url
def get_new_url(self):
new_url = self.new_urls.pop()
self.old_urls.add(new_url)return new_url
URL下载模块,负责把网页的内容下载下来,使用urllib2库进行下载。
#coding utf8import urllib2class HtmlDownloader(object):def download(self, url):
if url is None:
return Noneresponse = urllib2.urlopen(url);
if response.getcode == 200:
return Nonereturn response.read()
URL解析模块,使用Beautifulsoup把当前网页的其他链接和网页简介解析出来。
# coding:utf-8
import urlparsefrom bs4 import BeautifulSoup
import reclass HtmlParser(object):
def parser(self, page_url, html_content):
if page_url is None or html_content is None:
return
soup = BeautifulSoup(html_content, "html.parser", from_encoding="utf-8")
new_urls = self._get_new_urls(page_url, soup)
new_data = https://www.it610.com/article/self._get_new_data(page_url, soup)return new_urls, new_datadef _get_new_urls(self, page_url, soup):
new_urls = set()links = soup.find_all('a', href=https://www.it610.com/article/re.compile(r'/item/'))for link in links:
new_url = link["href"]
new_url_full = urlparse.urljoin(page_url, new_url)
new_urls.add(new_url_full)return new_urlsdef _get_new_data(self, page_url, soup):
res_data = https://www.it610.com/article/{}res_data['url'] = page_url# Python
title_node = soup.find('dd', class_="lemmaWgt-lemmaTitle-title").find('h1')
res_data['title'] = title_node.get_text()#
summary_node = soup.find("div", class_="lemma-summary")
res_data['summary'] = summary_node.get_text()return res_data
输出模块,负责把解析的网页内容保存起来。
#coding=utf-8class HtmlOutputer(object):def __init__(self):
self.datas = []def collect_data(self,data):
if data is None:
returnself.datas.append(data)def outpute_html(self):
fout = open("outputer.html",'w')
fout.write("")
fout.write("")
fout.write("")for data in self.datas:
fout.write("")
fout.write("%s " % data['url'])
fout.write(" %s " % data['title'].encode('utf-8'))
fout.write(" %s " % data['summary'].encode('utf-8'))
fout.write(" ")fout.write("")
fout.write("")
fout.write("
")
最后是调度模块,把各个模块之间的功能调度起来
#coding:utf8
import url_manager
import html_downloader
import html_outputer
import html_parserclass 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()
passdef craw(self, root_url):
self.urls._add_new_url(root_url)count = 1;
while self.urls.has_new_url():try:
new_url = self.urls.get_new_url()
print new_url#得到url的内容
html_content = self.downloader.download(new_url)#得到url的内容和url
new_urls,new_data = https://www.it610.com/article/self.parser.parser(new_url,html_content)self.urls.add_new_urls(new_urls)self.outputer.collect_data(new_data)
except:
print"splider failed"if (count == 10):
breakcount = count + 1;
self.outputer.outpute_html()if __name__ == "__main__":
root_url = "https://baike.baidu.com/item/Python/407313"obj_splider = SpiderMain()
obj_splider.craw(root_url)
工程目录如下:
文章图片
源码路径如下,感兴趣的朋友可以去下载:
https://github.com/HelloKittyNII/Spider/tree/master/%E7%99%BE%E5%BA%A6%E7%99%BE%E7%A7%91%E7%88%AC%E8%99%AB/baike_spider
推荐阅读
- 爬虫|若想拿下爬虫大单,怎能不会逆向爬虫,价值过万的逆向爬虫教程限时分享
- python|尚硅谷python爬虫(二)-解析方法
- web挖洞|HACK学习黑帽子Python--漏洞检测脚本快速编写
- Pyecharts|Pyecharts 猎聘招聘数据可视化
- Python爬虫笔记|Python爬虫学习笔记_DAY_17_Python爬虫之使用cookie绕过登录的介绍【Python爬虫】
- Python爬虫笔记|Python爬虫学习笔记_DAY_19_Python爬虫之代理ip与代理池的使用介绍【Python爬虫】
- Python爬虫笔记|Python爬虫学习笔记_DAY_18_Python爬虫之handler处理器的使用【Python爬虫】
- python|用 Python 写一副春联&福字,把最好的祝福,送给重要的人
- 爬虫|淘宝商品数据爬取
- 爬虫学习历程小记