1. 程式人生 > >Python學習(從Web抓取資訊)

Python學習(從Web抓取資訊)

一、利用webbrowser.open()開啟一個網站:

>>> import webbrowser
>>> webbrowser.open('http://i.firefoxchina.cn/?from=worldindex')
True

例項:使用指令碼開啟一個網頁。

所有Python程式的第一行都應以#!python開頭,它告訴計算機想讓Python來執行這個程式。(我沒帶這行試了試,也可以,可能這是一種規範吧)

1.sys.argv讀取命令列引數:開啟一個新的檔案編輯器視窗,輸入下面的程式碼,將其儲存為map.py

2.讀取剪貼簿內容:

3.呼叫webbrowser.open()

函式開啟外部瀏覽:

#! 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用法的,請參考這裡;不清楚.join()用法的,請參考這裡sys.argv
是字串的列表,所以將它傳遞給join()方法返回一個字串

好了,現在選中'天安門廣場'這幾個字並複製,然後到桌面雙擊你的程式。當然你也可以在命令列找到你的程式,然後輸入地點。

二、用requests模組從Web下載檔案requests模組不是Python自帶的,通過命令列執行pip install request安裝。沒翻牆是很難安裝成功的,手動安裝可以參考這裡

>>> import requests
>>> res = requests.get('http://i.firefoxchina.cn/?from=worldindex')    #向get中傳入一個網址
>>> type(res)    #響應物件
<class 'requests.models.Response'>
>>> print(res.status_code)    #響應碼
200
>>> res.text    #返回的文字
requests中檢視網上下載的檔案內容的方法還有很多,如果以後的部落格用的到,會做說明,在此不再一一介紹。在下載檔案的過程中,用raise_for_status()方法可以確保下載確實成功,然後再讓程式繼續做其他事情。
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')    #以寫二進位制模式開啟檔案,目的是儲存文字中的“Unicode編碼”
>>> for word in res.iter_content(100000):    #iter_content()方法在迴圈的每次迭代中返回一段bytes資料型別的內容,你需要指定其包含的位元組數
	file.write(word)

	
16997
>>> file.close()
四、用BeautifulSoup模組解析HTML在命令列中用pip install beautifulsoup4安裝它。

1.bs4.BeautifulSoup()函式可以解析HTML網站連結requests.get(),也可以解析本地儲存的HTML檔案,直接open()一個本地HTML頁面

>>> 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'>
我這裡有錯誤提示,所以加了第二個引數。
>>> 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()方法尋找元素:需傳入一個字串作為CSS“選擇器”來取得Web頁面相應元素,例如:

soup.select('div'):所有名為<div>的元素;

soup.select('#author'):帶有id屬性為author的元素;

soup.select('.notice'):所有使用CSS class屬性名為notice的元素;

soup.select('div span'):所有在<div>元素之內的<span>元素;

soup.select('input[name]'):所有名為<input>並有一個name屬性,其值無所謂的元素;

soup.select('input[type="button"]'):所有名為<input>並有一個type屬性,其值為button的元素。

想檢視更多的解析器,請參看這裡

>>> 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="stylesheet" type="text/css"/>, <link href="" id="moz-skin" rel="stylesheet" type="text/css"/>, <link href="" id="moz-dir" rel="stylesheet" type="text/css"/>, <link href="" id="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="stylesheet" type="text/css"/>
>>> link[0].attrs
{'rel': ['stylesheet'], 'type': 'text/css', 'href': 'css/mozMainStyle-min.css?v=20170705'}
3.通過元素的屬性獲取資料:接著上面的程式碼寫。
>>> link[0].get('href')
'css/mozMainStyle-min.css?v=20170705
上面這些方法也算是對“網路爬蟲”的一些初探。