實(shí)例講解Python爬取網(wǎng)頁(yè)數(shù)據(jù)
一、利用webbrowser.open()打開(kāi)一個(gè)網(wǎng)站:
>>> import webbrowser >>> webbrowser.open('http://i.firefoxchina.cn/?from=worldindex') True
實(shí)例:使用腳本打開(kāi)一個(gè)網(wǎng)頁(yè)。
所有Python程序的第一行都應(yīng)以#!python開(kāi)頭,它告訴計(jì)算機(jī)想讓Python來(lái)執(zhí)行這個(gè)程序。(我沒(méi)帶這行試了試,也可以,可能這是一種規(guī)范吧)
1.從sys.argv讀取命令行參數(shù):打開(kāi)一個(gè)新的文件編輯器窗口,輸入下面的代碼,將其保存為map.py。
2.讀取剪貼板內(nèi)容:
3.調(diào)用webbrowser.open()函數(shù)打開(kāi)外部瀏覽:
#! python3 import webbrowser, sys, pyperclip if len(sys.argv) > 1: mapAddress = ''.join(sys.argv[1:]) else: mapAddress = pyperclip.paste() webbrowser.open('http://map.baidu.com/?newmap=1&ie=utf-8&s=s%26wd%3D' + mapAddress
注:不清楚sys.argv用法的,請(qǐng)參考這里;不清楚.join()用法的,請(qǐng)參考這里。sys.argv是字符串的列表,所以將它傳遞給join()方法返回一個(gè)字符串。
好了,現(xiàn)在選中'天安門(mén)廣場(chǎng)'這幾個(gè)字并復(fù)制,然后到桌面雙擊你的程序。當(dāng)然你也可以在命令行找到你的程序,然后輸入地點(diǎn)。
二、用requests模塊從Web下載文件:requests模塊不是Python自帶的,通過(guò)命令行運(yùn)行pip install request安裝。沒(méi)翻墻是很難安裝成功的,手動(dòng)安裝可以參考這里。
>>> import requests >>> res = requests.get('http://i.firefoxchina.cn/?from=worldindex') #向get中傳入一個(gè)網(wǎng)址 >>> type(res) #響應(yīng)對(duì)象 <class 'requests.models.Response'> >>> print(res.status_code) #響應(yīng)碼 200 >>> res.text #返回的文本
requests中查看網(wǎng)上下載的文件內(nèi)容的方法還有很多,如果以后的博客用的到,會(huì)做說(shuō)明,在此不再一一介紹。在下載文件的過(guò)程中,用raise_for_status()方法可以確保下載確實(shí)成功,然后再讓程序繼續(xù)做其他事情。
import requests res = requests.get('http://i.firefoxchina.cn/?from=worldindex') try: res.raise_for_status() except Exception as exc: print('There was a problem: %s' % (exc))
三、將下載的文件保存到本地:
>>> import requests >>> res = requests.get('http://tech.firefox.sina.com/17/0820/10/6DKQALVRW5JHGE1I.html##0-tsina-1-13074-397232819ff9a47a7b7e80a40613cfe1') >>> res.raise_for_status() >>> file = open('1.txt', 'wb') #以寫(xiě)二進(jìn)制模式打開(kāi)文件,目的是保存文本中的“Unicode編碼” >>> for word in res.iter_content(100000): #<span class="fontstyle0"><span class="fontstyle0">iter_content()</span><span class="fontstyle1">方法在循環(huán)的每次迭代中返回一段</span><span class="fontstyle0">bytes</span><span class="fontstyle1">數(shù)據(jù)</span><span class="fontstyle1">類(lèi)型的內(nèi)容,你需要指定其包含的字節(jié)數(shù)</span></span> file.write(word) 16997 >>> file.close()
四、用BeautifulSoup模塊解析HTML:在命令行中用pip install beautifulsoup4安裝它。
1.bs4.BeautifulSoup()函數(shù)可以解析HTML網(wǎng)站鏈接requests.get(),也可以解析本地保存的HTML文件,直接open()一個(gè)本地HTML頁(yè)面。
>>> import requests, bs4 >>> res = requests.get('http://i.firefoxchina.cn/?from=worldindex') >>> res.raise_for_status() >>> soup = bs4.BeautifulSoup(res.text) Warning (from warnings module): File "C:\Users\King\AppData\Local\Programs\Python\Python36-32\lib\site-packages\beautifulsoup4-4.6.0-py3.6.egg\bs4\__init__.py", line 181 markup_type=markup_type)) UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently. The code that caused this warning is on line 1 of the file <string>. To get rid of this warning, change code that looks like this: BeautifulSoup(YOUR_MARKUP}) to this: BeautifulSoup(YOUR_MARKUP, "html.parser") >>> soup = bs4.BeautifulSoup(res.text, 'html.parser') >>> type(soup) <class 'bs4.BeautifulSoup'>
我這里有錯(cuò)誤提示,所以加了第二個(gè)參數(shù)。
>>> import bs4 >>> html = open('C:\\Users\\King\\Desktop\\1.htm') >>> exampleSoup = bs4.BeautifulSoup(html) >>> exampleSoup = bs4.BeautifulSoup(html, 'html.parser') >>> type(exampleSoup) <class 'bs4.BeautifulSoup'>
2.用select()方法尋找元素:需傳入一個(gè)字符串作為CSS“選擇器”來(lái)取得Web頁(yè)面相應(yīng)元素,例如:
soup.select('div'):所有名為<div>的元素;
soup.select('#author'):帶有id屬性為author的元素;
soup.select('.notice'):所有使用CSS class屬性名為notice的元素;
soup.select('div span'):所有在<div>元素之內(nèi)的<span>元素;
soup.select('input[name]'):所有名為<input>并有一個(gè)name屬性,其值無(wú)所謂的元素;
soup.select('input[type="button"]'):所有名為<input>并有一個(gè)type屬性,其值為button的元素。
想查看更多的解析器,請(qǐng)參看這里。
>>> import requests, bs4 >>> res = requests.get('http://i.firefoxchina.cn/?from=worldindex') >>> res.raise_for_status() >>> soup = bs4.BeautifulSoup(res.text, 'html.parser') >>> author = soup.select('#author') >>> print(author) [] >>> type(author) <class 'list'> >>> link = soup.select('link ') >>> print(link) [<link href="css/mozMainStyle-min.css?v=20170705" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css"/>, <link href="" id=" rel="external nofollow" rel="external nofollow" rel="external nofollow" moz-skin" rel="stylesheet" type="text/css"/>, <link href="" id=" rel="external nofollow" rel="external nofollow" rel="external nofollow" moz-dir" rel="stylesheet" type="text/css"/>, <link href="" id=" rel="external nofollow" rel="external nofollow" rel="external nofollow" moz-ver" rel="stylesheet" type="text/css"/>] >>> type(link) <class 'list'> >>> len(link) 4 >>> type(link[0]) <class 'bs4.element.Tag'> >>> link[0] <link href="css/mozMainStyle-min.css?v=20170705" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css"/> >>> link[0].attrs {'rel': ['stylesheet'], 'type': 'text/css', 'href': 'css/mozMainStyle-min.css?v=20170705'}
3.通過(guò)元素的屬性獲取數(shù)據(jù):接著上面的代碼寫(xiě)。
>>> link[0].get('href') 'css/mozMainStyle-min.css?v=20170705
上面這些方法也算是對(duì)“網(wǎng)絡(luò)爬蟲(chóng)”的一些初探。
- Python簡(jiǎn)單實(shí)現(xiàn)網(wǎng)頁(yè)內(nèi)容抓取功能示例
- Python 抓取動(dòng)態(tài)網(wǎng)頁(yè)內(nèi)容方案詳解
- 淺談如何使用python抓取網(wǎng)頁(yè)中的動(dòng)態(tài)數(shù)據(jù)實(shí)現(xiàn)
- python爬蟲(chóng)實(shí)現(xiàn)爬取同一個(gè)網(wǎng)站的多頁(yè)數(shù)據(jù)的實(shí)例講解
- 使用python實(shí)現(xiàn)抓取中國(guó)銀行外匯牌價(jià)首頁(yè)數(shù)據(jù)實(shí)現(xiàn)
相關(guān)文章
Python3爬取英雄聯(lián)盟英雄皮膚大圖實(shí)例代碼
這篇文章主要介紹了Python3爬取英雄聯(lián)盟英雄皮膚大圖的實(shí)例代碼,文中較詳細(xì)的給大家介紹了爬蟲(chóng)思路及完整代碼,需要的朋友可以參考下2018-11-11python入門(mén)課程第二講之怎么運(yùn)行Python
這篇文章主要介紹了python入門(mén)課程第二講之怎么運(yùn)行Python,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09python一行sql太長(zhǎng)折成多行并且有多個(gè)參數(shù)的方法
今天小編就為大家分享一篇python一行sql太長(zhǎng)折成多行并且有多個(gè)參數(shù)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07Python靜態(tài)類(lèi)型檢查新工具之pyright 使用指南
這篇文章主要介紹了Python靜態(tài)類(lèi)型檢查新工具之pyright 使用指南,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04Python?urllib?入門(mén)使用詳細(xì)教程
urllib?庫(kù),它是?Python?內(nèi)置的?HTTP?請(qǐng)求庫(kù),不需要額外安裝即可使用,這篇文章主要介紹了Python?urllib?入門(mén)使用,需要的朋友可以參考下2022-11-11python email smtplib模塊發(fā)送郵件代碼實(shí)例
本篇文章給大家分享了python email smtplib模塊發(fā)送郵件的相關(guān)代碼分享,有需要的朋友參考學(xué)習(xí)下。2018-04-04用sqlalchemy構(gòu)建Django連接池的實(shí)例
今天小編就為大家分享一篇用sqlalchemy構(gòu)建Django連接池的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08Python 手動(dòng)導(dǎo)包的實(shí)現(xiàn)
本文主要介紹了Python 手動(dòng)導(dǎo)包的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03