网络爬虫中进行数据抓取
以下內容是《用python寫網絡爬蟲》的讀書筆記
一、安裝firebug lite
firebug lite是一個用于在網站中查看調試html,css和javascript的有效工具。它現在可以安裝在chrome和firefox瀏覽器上。chrome瀏覽器的安裝教程。firefox瀏覽器的安裝教程。
二、三種頁面抓取方式
(1)正則表達式
正則表達式是我們進行數據獲取的最基本的方式,不了解正則表達式的,可以參看正則表達式的基本用法。
我們可以先下載html數據,然后用正則表達式對html中的數據進行匹配。以下是一個簡單的用法樣例:
url = "http://www.cnblogs.com/xudong-bupt/p/3586889.html" html = download(url) list = re.findall('<div class="BlogStats">(.*?)</div>', html) print list[0]這個樣例的作用是能夠打印出html文件中第一個<div class = "BlogStats"></div>之間的內容。
用正則表達式來獲取數據,優點是形式簡單,缺點是很難獲得健壯的正則表達式,當頁面發生細微變化時,正則表達式可能就不起作用了。
(2)Beautiful Soup
在開始之前內,首先我們需要在python中安裝beautifulsoup模塊,我使用 pip install beautifulsoup4,來進行模塊的安裝。它的相關方法可查閱其官方文檔
現在我們來執行一個小樣例:
from bs4 import BeautifulSoup from Chapter1.Background_Research import * def tes_example():'''use a broken_html to test the beautiful soup:return:'''broken_html = "<url class=country><li>Area <li>Population</url>"# use beautiful soup to parse the broken_htmlsoup = BeautifulSoup(broken_html, 'html.parser')fixed_html = soup.prettify()print fixed_htmldef find_text(url, id_name):'''find the lable text which id is equal to id_name:param url: the url of the html:param id_name: locate the special id:return: the text between the special label'''html = download(url)soup = BeautifulSoup(html, "html.parser")tr = soup.find(attrs={'id': id_name})text = tr.textreturn text text = find_text("http://www.cnpythoner.com/post/300.html", 'title') print text(3)Lxml
Lxml?是基于libxml2這個xml解析庫的python封裝。該模塊使用c語言編寫,解析速度比beautiful soup更快,不過安裝教程也更為復雜,附上最新的安裝說明。
Lxml和beautiful soup相比有一個明顯的優點就是它能夠使用css選擇器進行數據抽取。它已經能夠實現大部分的css3屬性,但是還有一部分是不支持的。具體可參看它的說明文檔。
下面是Lxml使用的一個小樣例:
import lxml.htmlfrom Chapter1.Background_Research import download
def test_lxml():
'''
use a broken_html to test the beautiful soup
:return:
'''
broken_html = "<url class="country"><li>Area <li>Population</url>"
# use beautiful soup to parse the broken_html
parse_html = lxml.html.fromstring(broken_html)
fixed_html = lxml.html.tostring(parse_html, pretty_print=True)
print fixed_html
test_lxml()
def find_text(url, id_name):
'''
it can get all text of label a under the div which id is id_name
:param url: given a url
:param id_name: define the special id name
:return: all text
'''
html = download(url)
tree_html = lxml.html.fromstring(html)
td = tree_html.cssselect('div#'+id_name+'> a')
values = []
for d in td:
values.append(d.text_content())
return values
values = find_text("http://www.cnpythoner.com/post/300.html", 'bdshare')
for value in values:
print value
?
轉載于:https://www.cnblogs.com/whatyouknow123/p/7725119.html
總結
以上是生活随笔為你收集整理的网络爬虫中进行数据抓取的全部內容,希望文章能夠幫你解決所遇到的問題。

- 上一篇: mysql主从部署
- 下一篇: oracle简单命令