1. 如何用python抓取這個網頁的內容
Python實現常規的靜態網頁抓取時,往往是用urllib2來獲取整個HTML頁面,然後從HTML文件中逐字查找對應的關鍵字。如下所示:
復制代碼代碼如下:
import urllib2
url="網址"
up=urllib2.urlopen(url)#打開目標頁面,存入變數up
cont=up.read()#從up中讀入該HTML文件
key1='<a href="http'#設置關鍵字1
key2="target"#設置關鍵字2
pa=cont.find(key1)#找出關鍵字1的位置
pt=cont.find(key2,pa)#找出關鍵字2的位置(從字1後面開始查找)
urlx=cont[pa:pt]#得到關鍵字1與關鍵字2之間的內容(即想要的數據)
print urlx
2. 如何用python抓取網頁上的數據
使用內置的包來抓取,就是在模仿瀏覽器訪問頁面,再把頁面的數據給解析出來,也可以看做是一次請求。
3. 求python抓網頁的代碼
python3.x中使用urllib.request模塊來抓取網頁代碼,通過urllib.request.urlopen函數取網頁內容,獲取的為數據流,通過read()函數把數字讀取出來,再把讀取的二進制數據通過decode函數解碼(編號可以通過查看網頁源代碼中<meta http-equiv="content-type" content="text/html;charset=gbk" />得知,如下例中為gbk編碼。),這樣就得到了網頁的源代碼。
如下例所示,抓取本頁代碼:
importurllib.request
html=urllib.request.urlopen('
).read().decode('gbk')#注意抓取後要按網頁編碼進行解碼
print(html)
以下為urllib.request.urlopen函數說明:
urllib.request.urlopen(url,
data=None, [timeout, ]*, cafile=None, capath=None,
cadefault=False, context=None)
Open the URL url, which can be either a string or a Request object.
data must be a bytes object specifying additional data to be sent to
the server, or None
if no such data is needed. data may also be an iterable object and in
that case Content-Length value must be specified in the headers. Currently HTTP
requests are the only ones that use data; the HTTP request will be a
POST instead of a GET when the data parameter is provided.
data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.parse.urlencode() function takes a mapping or
sequence of 2-tuples and returns a string in this format. It should be encoded
to bytes before being used as the data parameter. The charset parameter
in Content-Type
header may be used to specify the encoding. If charset parameter is not sent
with the Content-Type header, the server following the HTTP 1.1 recommendation
may assume that the data is encoded in ISO-8859-1 encoding. It is advisable to
use charset parameter with encoding used in Content-Type header with the Request.
urllib.request mole uses HTTP/1.1 and includes Connection:close header
in its HTTP requests.
The optional timeout parameter specifies a timeout in seconds for
blocking operations like the connection attempt (if not specified, the global
default timeout setting will be used). This actually only works for HTTP, HTTPS
and FTP connections.
If context is specified, it must be a ssl.SSLContext instance describing the various SSL
options. See HTTPSConnection for more details.
The optional cafile and capath parameters specify a set of
trusted CA certificates for HTTPS requests. cafile should point to a
single file containing a bundle of CA certificates, whereas capath
should point to a directory of hashed certificate files. More information can be
found in ssl.SSLContext.load_verify_locations().
The cadefault parameter is ignored.
For http and https urls, this function returns a http.client.HTTPResponse object which has the
following HTTPResponse
Objects methods.
For ftp, file, and data urls and requests explicitly handled by legacy URLopener and FancyURLopener classes, this function returns a
urllib.response.addinfourl object which can work as context manager and has methods such as
geturl() — return the URL of the resource retrieved,
commonly used to determine if a redirect was followed
info() — return the meta-information of the page, such
as headers, in the form of an email.message_from_string() instance (see Quick
Reference to HTTP Headers)
getcode() – return the HTTP status code of the response.
Raises URLError on errors.
Note that None
may be returned if no handler handles the request (though the default installed
global OpenerDirector uses UnknownHandler to ensure this never happens).
In addition, if proxy settings are detected (for example, when a *_proxy environment
variable like http_proxy is set), ProxyHandler is default installed and makes sure the
requests are handled through the proxy.
The legacy urllib.urlopen function from Python 2.6 and earlier has
been discontinued; urllib.request.urlopen() corresponds to the old
urllib2.urlopen.
Proxy handling, which was done by passing a dictionary parameter to urllib.urlopen, can be
obtained by using ProxyHandler objects.
Changed in version 3.2: cafile
and capath were added.
Changed in version 3.2: HTTPS virtual
hosts are now supported if possible (that is, if ssl.HAS_SNI is true).
New in version 3.2: data can be
an iterable object.
Changed in version 3.3: cadefault
was added.
Changed in version 3.4.3: context
was added.
4. 如何用 Python 實現 Web 抓取
Web 抓取的定義
Web 抓取是抽取網路數據的過程。只要藉助合適的工具,任何你能看到的數據都可以進行抽取。在本文中,我們將重點介紹自動化抽取過程的程序,幫助你在較短時間內收集大量數據。除了筆者前文提到的用例,抓取技術的用途還包括:SEO 追蹤、工作追蹤、新聞分析以及筆者的最愛——社交媒體的情感分析!
一點提醒
在開啟 Web 抓取的探險之前,請確保自己了解相關的法律問題。許多網站在其服務條款中明確禁止對其內容進行抓取。例如,Medium 網站就寫道:「遵照網站 robots.txt 文件中的規定進行的爬取操作(Crawling)是可接受的,但是我們禁止抓取(Scraping)操作。」對不允許抓取的網站進行抓取可能會使你進入他們的黑名單!與任何工具一樣,Web 抓取也可能用於復制網站內容之類的不良目的。此外,由 Web 抓取引起的法律訴訟也不在少數。
設置代碼
在充分了解小心行事的必要之後,讓我們開始學習 Web 抓取。其實,Web 抓取可以通過任何編程語言實現,在不久之前,我們使用 Node 實現過。在本文中,考慮到其簡潔性與豐富的包支持,我們將使用 Python 實現抓取程序。
Web 抓取的基本過程
當你打開網路中的某個站點時,就會下載其 HTML 代碼,由你的 web 瀏覽器對其進行分析與展示。該 HTML 代碼包含了你所看到的所有信息。因此,通過分析 HTML 代碼就能得到所需信息(比如價格)。你可以使用正則表達式在數據海洋中搜索你需要的信息,也可以使用函數庫來解釋 HTML,同樣也能得到需要數據。
在 Python 中,我們將使用一個名為靚湯(Beautiful Soup)的模塊對 HTML 數據進行分析。你可以藉助 pip 之類的安裝程序安裝之,運行如下代碼即可:
pip install beautifulsoup4
或者,你也可以根據源碼進行構建。在該模塊的文檔說明頁,可以看到詳細的安裝步驟。
安裝完成之後,我們大致會遵循以下步驟實現 web 抓取:
向 URL 發送請求
接收響應
分析響應以尋找所需數據
作為演示,我們將使用筆者的博客 http://dada.theblogbowl.in/. 作為目標 URL。
前兩個步驟相對簡單,可以這樣完成:
from urllib import urlopen#Sending the http requestwebpage = urlopen('http://my_website.com/').read()
接下來,將響應傳給之前安裝的模塊:
from bs4 import BeautifulSoup#making the soup! yummy ;)soup = BeautifulSoup(webpage, "html5lib")
請注意,此處我們選擇了 html5lib 作為解析器。根據 BeautifulSoup 的文檔,你也可以為其選擇不同的解析器。
解析 HTML
在將 HTML 傳給 BeautifulSoup 之後,我們可以嘗試一些指令。譬如,檢查 HTML 標記代碼是否正確,可以驗證該頁面的標題(在 Python 解釋器中):
>>> soup.title<title>Transcendental Tech Talk</title>>>> soup.title.text
u'Transcendental Tech Talk'
>>>
接下來,開始抽取頁面中的特定元素。譬如,我想抽取博客中文章標題的列表。為此,我需要分析 HTML 的結構,這一點可以藉助 Chrome 檢查器完成。其他瀏覽器也提供了類似的工具。
使用 Chrome 檢查器檢查某個頁面的 HTML 結構
如你所見,所有文章標題都帶有 h3 標簽與兩個類屬性:post-title 與 entry-title 類。因此,用 post-title類搜索所有 h3 元素就能得到該頁的文章標題列表。在此例中,我們使用 BeautifulSoup 提供的 find_all 函數,並通過 class_ 參數確定所需的類:
>>> titles = soup.find_all('h3', class_ = 'post-title') #Getting all titles>>> titles[0].textu'\nKolkata #BergerXP IndiBlogger meet, Marketing Insights, and some Blogging Tips\n'>>>
只通過 post-title 類進行條目搜索應該可以得到相同的結果:
>>> titles = soup.find_all(class_ = 'post-title') #Getting all items with class post-title>>> titles[0].textu'\nKolkata #BergerXP
IndiBlogger meet, Marketing Insights, and some Blogging Tips\n'>>>
5. 如何用Python爬蟲抓取網頁內容
爬蟲流程
其實把網路爬蟲抽象開來看,它無外乎包含如下幾個步驟
模擬請求網頁。模擬瀏覽器,打開目標網站。
獲取數據。打開網站之後,就可以自動化的獲取我們所需要的網站數據。
保存數據。拿到數據之後,需要持久化到本地文件或者資料庫等存儲設備中。
那麼我們該如何使用 Python 來編寫自己的爬蟲程序呢,在這里我要重點介紹一個 Python 庫:Requests。
Requests 使用
Requests 庫是 Python 中發起 HTTP 請求的庫,使用非常方便簡單。
模擬發送 HTTP 請求
發送 GET 請求
當我們用瀏覽器打開豆瓣首頁時,其實發送的最原始的請求就是 GET 請求
import requests
res = requests.get('http://www.douban.com')
print(res)
print(type(res))
>>>
<Response [200]>
<class 'requests.models.Response'>
6. 如何用 Python 實現 Web 抓取
給你一個例子 以下代碼調試通過:
#coding=utf-8
importurllib
defgetHtml(url):
page=urllib.urlopen(url)
html=page.read()
returnhtml
html=getHtml("https://.com/")
printhtml
運行效果:
7. Python爬蟲是什麼
網路爬蟲(又被稱為網頁蜘蛛,網路機器人,在FOAF社區中間,更經常的稱為網頁追逐者),是一種按照一定的規則,自動地抓取萬維網信息的程序或者腳本。另外一些不常使用的名字還有螞蟻、自動索引、模擬程序或者蠕蟲。
其實通俗的講就是通過程序去獲取web頁面上自己想要的數據,也就是自動抓取數據。
爬蟲可以做什麼?
你可以用爬蟲爬圖片,爬取視頻等等你想要爬取的數據,只要你能通過瀏覽器訪問的數據都可以通過爬蟲獲取。
爬蟲的本質是什麼?
模擬瀏覽器打開網頁,獲取網頁中我們想要的那部分數據
瀏覽器打開網頁的過程:
當你在瀏覽器中輸入地址後,經過DNS伺服器找到伺服器主機,向伺服器發送一個請求,伺服器經過解析後發送給用戶瀏覽器結果,包括html,js,css等文件內容,瀏覽器解析出來最後呈現給用戶在瀏覽器上看到的結果。
所以用戶看到的瀏覽器的結果就是由HTML代碼構成的,我們爬蟲就是為了獲取這些內容,通過分析和過濾html代碼,從中獲取我們想要資源。
8. 如何用python抓取網頁特定內容
最簡單可以用urllib,python2.x和python3.x的用法不同,以python2.x為例:
importurllib
html=urllib.open(url)
text=html.read()
復雜些可以用requests庫,支持各種請求類型,支持cookies,header等
再復雜些的可以用selenium,支持抓取javascript產生的文本
我設計了簡單的爬蟲闖關網站 www.heibanke.com/lesson/crawler_ex00/
新手如果能自己把三關闖過,相信一定會有所收獲。
題解在課程里有提到http://study.163.com/course/courseMain.htm?courseId=1000035
9. 如何用 Python 實現 Web 抓取
#!/usr/bin/envpython
#-*-coding:utf-8-*-
#bycarlin.wang
#請參考
importurllib
importurllib2
importtime
importos
importrandom
frombs4importBeautifulSoup
defget_Html(url):
headers={"User-Agent":"Mozilla/5.0(WindowsNT6.1;WOW64;rv:41.0)Gecko/20100101Firefox/41.0"}
req=urllib2.Request(url,headers=headers)
res=urllib2.urlopen(req)
res_html=res.read().decode('UTF-8')
returnres_html
defurlPages(page):
url="http://jandan.net/ooxx/page-"+str(page)+'#comments'
returnurl
deffind_img_url(html):
soup=BeautifulSoup(html,'html.parser',from_encoding='utf-8')
img_urls=soup.find_all(class_='view_img_link')
returnimg_urlsdefdownload_img(url):
fdir="D:/data/jiandan"
ifnotos.path.exists(fdir):
os.makedirs(fdir)
try:
#(p2)=os.path.split(url)
#(p2,f2)=os.path.split(url)
f2=''.join(map(lambdaxx:(hex(ord(xx))[2:]),os.urandom(16)))#隨機字元串作為文件名字,防止名字重復
#ifos.path.exists(fdir+"/"+f2):
#print"fdirisexists"
ifurl:
imgtype=url.split('/')[4].split('.')[1]
filename,msg=urllib.urlretrieve(url,fdir+"/"+f2+'.'+imgtype)
ifos.path.getsize(filename)<100:
os.remove(filename)
exceptException,e:
return"downimageerror!"
defrun():
forpageinrange(2001,2007):
html=get_Html(urlPages(page))
urls=find_img_url(html)
forurlinurls:
s=url.get('href')
prints
download_img(s)
if__name__=='__main__':
run()