python爬蟲入門教程 Python 爬蟲介紹

2021-10-10 03:51:44 字數 2493 閱讀 5964

一、什麼是爬蟲

爬蟲:一段自動抓取網際網路資訊的程式,從網際網路上抓取對於我們有價值的資訊。

二、python爬蟲架構

網頁解析器:將乙個網頁字串進行解析,可以按照我們的要求來提取出我們有用的資訊,也可以根據dom樹的解析方式來解析。網頁解析器有正規表示式(直觀,將網頁轉成字串通過模糊匹配的方式來提取有價值的資訊,當文件比較複雜的時候,該方法提取資料的時候就會非常的困難)、html.parser(python自帶的)、beautifulsoup(第三方外掛程式,可以使用python自帶的html.parser進行解析,也可以使用lxml進行解析,相對於其他幾種來說要強大一些)、lxml(第三方外掛程式,可以解析 xml 和 html),html.parser 和 beautifulsoup 以及 lxml 都是以 dom 樹的方式進行解析的。

應用程式:就是從網頁中提取的有用資料組成的乙個應用。

下面用乙個圖來解釋一下排程器是如何協調工作的:

#!/usr/bin/python# -*- coding: utf-8 -*-importcookielibimporturllib2url=""response1=urllib2.urlopen(url)print"第一種方法"#獲取狀態碼,200表示成功printresponse1.getcode()#獲取網頁內容的長度printlen(response1.read())print"第二種方法"request=urllib2.request(url)#模擬mozilla瀏覽器進行爬蟲request.add_header("user-agent","mozilla/5.0")response2=urllib2.urlopen(request)printresponse2.getcode()printlen(response2.read())print"第三種方法"cookie=cookielib.cookiejar()#加入urllib2處理cookie的能力opener=urllib2.build_opener(urllib2.httpcookieprocessor(cookie))urllib2.install_opener(opener)response3=urllib2.urlopen(url)printresponse3.getcode()printlen(response3.read())printcookie

四、第三方庫 beautiful soup 的安裝

beautiful soup: python 的第三方外掛程式用來提取 xml 和 html 中的資料,官網位址

1、安裝 beautiful soup

開啟 cmd(命令提示符),進入到 python(python2.7版本)安裝目錄中的 scripts 下,輸入 dir 檢視是否有 pip.exe, 如果用就可以使用 python 自帶的 pip 命令進行安裝,輸入以下命令進行安裝即可:

pip install beautifulsoup4

2、測試是否安裝成功

編寫乙個 python 檔案,輸入:

import bs4

print bs4

執行該檔案,如果能夠正常輸出則安裝成功。

五、使用 beautiful soup 解析 html 檔案

#!/usr/bin/python# -*- coding: utf-8 -*-importrefrombs4importbeautifulsouphtml_doc="""

the dormouse's story

the dormouse's story

once upon a time there were three little sisters; and their names were

elsie,

lacie and

tillie;

and they lived at the bottom of a well.

..."""#建立乙個beautifulsoup解析物件soup=beautifulsoup(html_doc,"html.parser",from_encoding="utf-8")#獲取所有的鏈結links=soup.find_all('a')print"所有的鏈結"forlinkinlinks:printlink.name,link['href'],link.get_text()print"獲取特定的url位址"link_node=soup.find('a',href="")printlink_node.name,link_node['href'],link_node['class'],link_node.get_text()print"正規表示式匹配"link_node=soup.find('a',href=re.compile(r"ti"))printlink_node.name,link_node['href'],link_node['class'],link_node.get_text()print"獲取p段落的文字"p_node=soup.find('p',class_='story')printp_node.name,p_node['class'],p_node.get_text()

python爬蟲入門教程

前言 在爬蟲系列文章 優雅的http庫requests 中介紹了 requests 的使用方式,這一次我們用 requests 構建乙個知乎 api,功能包括 私信傳送 文章點讚 使用者關注等,因為任何涉及使用者操作的功能都需要登入後才操作,所以在閱讀這篇文章前建議先了解python模擬知乎登入 現...

python爬蟲(1) 入門教程

網頁一般由三部分組成,分別是 html 超文字標記語言 css 層疊樣式表 和 jscript 活動指令碼語言 1 html html 是整個網頁的結構,相當於整個 的框架。帶 符號的都是屬於 html 的標籤,並且標籤都是成對出現的。2 css css 表示樣式,圖 1 中第 13 行 style...

Python爬蟲入門教程,通過爬蟲實戰學會爬蟲。

未完待續 requests簡介 python中原生的一款基於網路請求的模組,功能強大,簡單便捷,效率極高.作用 模擬遊覽器請求。安裝 pip install requests 使用 指定url 發起請求 獲取響應資料 持久化儲存 import requests if name main 指定url ...