python網路爬蟲步驟:首先準備所需庫,編寫爬蟲調度程序;然後編寫url管理器,並編寫網頁下載器;接著編寫網頁解析器;最後編寫網頁輸出器即可。
本教學操作環境:windows7系統、python3.9版,DELL G3電腦。
python網路爬蟲步驟
(1)準備所需庫
我們需要準備一款名為BeautifulSoup(網頁解析)的開源函式庫,用來對下載的網頁進行解析,我們是用的是PyCharm編譯環境所以可以直接下載該開源函式庫。
步驟如下:
選擇File->Settings
#開啟Project:PythonProject下的Project interpreter
#點選加號新增新的函式庫
#輸入bs4選擇bs4點選Install Packge進行下載
(2)寫爬蟲調度程式
這裡的bike_spider是專案名稱引入的四個類別分別對應下面的四段程式碼url管理器,url下載器, url解析器,url輸出器。
# 爬虫调度程序 from bike_spider import url_manager, html_downloader, html_parser, html_outputer # 爬虫初始化 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, my_root_url): count = 1 self.urls.add_new_url(my_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 == 10: break count += 1 except: print("craw failed") self.outputer.output_html() if __name__ == "__main__": root_url = "http://baike.baidu.com/item/Python/407313" obj_spider = SpiderMain() obj_spider.craw(root_url)
(4)編寫網頁下載器##########透過網路請求來下載頁面###(3)編寫url管理器我們把已經爬取過的url和未爬取的url分開存放以便我們不會重複爬取某些已經爬取過的網頁。
# url管理器 class UrlManager(object): def __init__(self): self.new_urls = set() self.old_urls = set() 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) def add_new_urls(self, urls): if urls is None or len(urls) == 0: return for url in urls: self.new_urls.add(url) def get_new_url(self): # pop方法会帮我们获取一个url并且移除它 new_url = self.new_urls.pop() self.old_urls.add(new_url) return new_url def has_new_url(self): return len(self.new_urls) != 0登入後複製
# 网页下载器 import urllib.request class HtmlDownloader(object): def download(self, url): if url is None: return None response = urllib.request.urlopen(url) # code不为200则请求失败 if response.getcode() != 200: return None return response.read()
# 网页解析器 import re from bs4 import BeautifulSoup from urllib.parse import urljoin class HtmlParser(object): def parse(self, page_url, html_cont): if page_url is None or html_cont is None: return soup = BeautifulSoup(html_cont, "html.parser", from_encoding="utf-8") new_urls = self._get_new_urls(page_url, soup) new_data = self._get_new_data(page_url, soup) return new_urls, new_data def _get_new_data(self, page_url, soup): res_data = {"url": page_url} # 获取标题 title_node = soup.find("dd", class_="lemmaWgt-lemmaTitle-title").find("h1") res_data["title"] = title_node.get_text() summary_node = soup.find("p", class_="lemma-summary") res_data["summary"] = summary_node.get_text() return res_data def _get_new_urls(self, page_url, soup): new_urls = set() # 查找出所有符合下列条件的url links = soup.find_all("a", href=re.compile(r"/item/")) for link in links: new_url = link['href'] # 获取到的url不完整,学要拼接 new_full_url = urljoin(page_url, new_url) new_urls.add(new_full_url) return new_urls
# 网页输出器 class HtmlOutputer(object): def __init__(self): self.datas = [] def collect_data(self, data): if data is None: return self.datas.append(data) # 我们以html表格形式进行输出 def output_html(self): fout = open("output.html", "w", encoding='utf-8') fout.write("<html>") fout.write("<meta charset='utf-8'>") fout.write("<body>") # 以表格输出 fout.write("<table>") for data in self.datas: # 一行 fout.write("<tr>") # 每个单元行的内容 fout.write("<td>%s</td>" % data["url"]) fout.write("<td>%s</td>" % data["title"]) fout.write("<td>%s</td>" % data["summary"]) fout.write("</tr>") fout.write("</table>") fout.write("</body>") fout.write("</html>") # 输出完毕后一定要关闭输出器 fout.close()
以上是python網路爬蟲步驟是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!