掃二維碼與項目經理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯網交流
網絡爬蟲(又被稱為網頁蜘蛛,網絡機器人,在FOAF社區(qū)中間,更經常的稱為網頁追逐者),是一種按照一定的規(guī)則,自動地抓取萬維網信息的程序或者腳本。另外一些不常使用的名字還有螞蟻、自動索引、模擬程序或者蠕蟲。

創(chuàng)新互聯建站專業(yè)為企業(yè)提供城陽網站建設、城陽做網站、城陽網站設計、城陽網站制作等企業(yè)網站建設、網頁設計與制作、城陽企業(yè)網站模板建站服務,十多年城陽做網站經驗,不只是建網站,更提供有價值的思路和整體網絡服務。
其實通俗的講就是通過程序去獲取web頁面上自己想要的數據,也就是自動抓取數據
Python 爬蟲架構主要由五個部分組成,分別是調度器、URL管理器、網頁下載器、網頁解析器、應用程序(爬取的有價值數據)。
下面用一個圖來解釋一下調度器是如何協調工作的:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import cookielib
import urllib2
url = "http://www.baidu.com"
response1 = urllib2.urlopen(url)
print "第一種方法"
#獲取狀態(tài)碼,200表示成功
print response1.getcode()
#獲取網頁內容的長度
print len(response1.read())
print "第二種方法"
request = urllib2.Request(url)
#模擬Mozilla瀏覽器進行爬蟲
request.add_header("user-agent","Mozilla/5.0")
response2 = urllib2.urlopen(request)
print response2.getcode()
print len(response2.read())
print "第三種方法"
cookie = cookielib.CookieJar()
#加入urllib2處理cookie的能力
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
urllib2.install_opener(opener)
response3 = urllib2.urlopen(url)
print response3.getcode()
print len(response3.read())
print cookie
Beautiful Soup: Python 的第三方插件用來提取 xml 和 HTML 中的數據,官網地址
https://www.crummy.com/software/BeautifulSoup/
安裝 Beautiful Soup
打開 cmd(命令提示符),進入到 Python(Python2.7版本)安裝目錄中的 scripts 下,輸入 dir 查看是否有 pip.exe, 如果用就可以使用 Python 自帶的 pip 命令進行安裝,輸入以下命令進行安裝即可:
pip install beautifulsoup4
編寫一個 Python 文件,輸入:
#!/usr/bin/python # –– coding: UTF-8 –– import re from bs4 import BeautifulSoup html_doc = “””
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.
…
“”” #創(chuàng)建一個BeautifulSoup解析對象 soup = BeautifulSoup(html_doc,”html.parser”,from_encoding=”utf-8″) #獲取所有的鏈接 links = soup.find_all(‘a’) print “所有的鏈接” for link in links: print link.name,link[‘href’],link.get_text() print “獲取特定的URL地址” link_node = soup.find(‘a’,href=”http://example.com/elsie”) print link_node.name,link_node[‘href’],link_node[‘class’],link_node.get_text() print “正則表達式匹配” link_node = soup.find(‘a’,href=re.compile(r”ti”)) print link_node.name,link_node[‘href’],link_node[‘class’],link_node.get_text() print “獲取P段落的文字” p_node = soup.find(‘p’,class_=’story’) print p_node.name,p_node[‘class’],p_node.get_text()

我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯網交流