日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

网络爬虫中进行数据抓取

發布時間:2025/7/25 61 豆豆
生活随笔 收集整理的這篇文章主要介紹了 网络爬虫中进行数据抓取 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

以下內容是《用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.html
from 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

總結

以上是生活随笔為你收集整理的网络爬虫中进行数据抓取的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。