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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

python爬虫从网页下载文件_用 Python爬虫下载网页文件教程-ie缓存文件提取器

發布時間:2023/12/10 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python爬虫从网页下载文件_用 Python爬虫下载网页文件教程-ie缓存文件提取器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

什么是爬蟲

爬蟲:一段自動抓取互聯網信息的程序,從互聯網上抓取對于我們有價值的信息。

Python爬蟲架構

Python 爬蟲架構主要由五個部分組成,分別是調度器、URL管理器、網頁下載器、網頁解析器、應用程序(爬取的有價值數據)。調度器:相當于一臺電腦的CPU,主要負責調度URL管理器、下載器、解析器之間的協調工作。

URL管理器:包括待爬取的URL地址和已爬取的URL地址,防止重復抓取URL和循環抓取URL,實現URL管理器主要用三種方式,通過內存、數據庫、緩存數據庫來實現。

網頁下載器:通過傳入一個URL地址來下載網頁,將網頁轉換成一個字符串,網頁下載器有urllib2(Python官方基礎模塊)包括需要登錄、代理、和cookie,requests(第三方包)

網頁解析器:將一個網頁字符串進行解析,可以按照我們的要求來提取出我們有用的信息,也可以根據DOM樹的解析方式來解析。網頁解析器有正則表達式(直觀,將網頁轉成字符串通過模糊匹配的方式來提取有價值的信息,當文檔比較復雜的時候,該方法提取數據的時候就會非常的困難)、html.parser(Python自帶的)、beautifulsoup(第三方插件,可以使用Python自帶的html.parser進行解析,也可以使用lxml進行解析,相對于其他幾種來說要強大一些)、lxml(第三方插件,可以解析 xml 和 HTML),html.parser 和 beautifulsoup 以及 lxml 都是以 DOM 樹的方式進行解析的。

應用程序:就是從網頁中提取的有用數據組成的一個應用。

使用urllib2 實現下載網頁的方式#!/usr/bin/python

# -*- coding: UTF-8 -*-

import cookielib

import urllib2

url = "http://www.baidu.com"

response1 = urllib2.urlopen(url)

print "第一種方法"

#獲取狀態碼,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 解析 html 文件#!/usr/bin/python

# -*- coding: UTF-8 -*-

import re

from bs4 import BeautifulSoup

html_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 "所有的鏈接"

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()shsh

python是不是挺厲害的呢

總結

以上是生活随笔為你收集整理的python爬虫从网页下载文件_用 Python爬虫下载网页文件教程-ie缓存文件提取器的全部內容,希望文章能夠幫你解決所遇到的問題。

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