從Web抓取信息
一、webbrowser模塊——打開瀏覽器獲取指定頁面
open()函數 能夠啟動一個新瀏覽器
#!python 3 #!mapIt.py - Launches a map in the browser using an address from the command line or clipboard. import webbrowser, sys, pyperclip if len(sys.argv) > 1: address = ‘ ‘.join(sys.argv[1:]) # Get address from command line. else: address= pyperclip.paste() # Get address from clipboard. webbrowser.open(‘https://www.google.com/map/place/‘ + address)
二、requests模塊——從Internet上下載文件和網頁
下載並保存到文件的步驟:
①調用requests.get()下載該文件
②用‘wb‘調用open(),以寫二進制的方式打開一個新文件
③利用Respose對象的iter_content()方法循環
④在每次叠代中調用write(),將內容寫入該文件
⑤調用close()關閉該文件
import requests res = requests.get(‘http://www.gutenberg.org/cache/epub/1112/pg1112.txt‘) res.raise_for_status() # 確保程序在下載失敗時停止 playFile = open(‘RomeoAndJuliet.txt‘, ‘wb‘) for chunk in res.iter_content(100000): playFile.write(chunk) 100000 78981 playFile.close()
三、Beautiful Soup——解析HTML,即網頁編寫格式
1. bs4.BeautufulSoup() 返回一個BeautifulSoup對象
2. soup.select() 方法返回一個Tag對象的列表,是BeautifulSoup表示一個HTML元素的方式
CSS選擇器(網絡上有各個示例)
3. getText() 方法返回該元素文本,或內部HTML
4. get() 方法返回屬性值
#! python3 # lucky.py - Open several Google search results. import requests, sys, webbrowser, bs4 print(‘Googling... ‘) # display text while downloading the Google page res = requests.get(‘http://google.com/search?q=‘ + ‘ ‘.join(sys.argv[1: ])) res.raise_for_status() soup = bs4.BeautifulSoup(res.text) # Retrieve top search result links. linkElems = soup.select(‘.r a‘) # Open a browser tab for each result. numOpen = min(5, len(linkElems)) for i in range(numOpen): webbrowser.open(‘http://google.com‘ + linkElems[i].get(‘href‘))
四、selenium——啟動並控制一個Web瀏覽器
(selenium能夠填寫表單,並模擬鼠標在這個瀏覽器中點擊)
1. 啟動 selenium 控制的瀏覽器
>>> from selenium import webdriver >>> browser = webdriver.Firefox() >>> type(browser) <class ‘selenium.webdriver.Firefox.webdriver.WebDriver‘> >>> browser.get(‘http://inventwithpython.com‘)
2. 在頁面中尋找元素
1. find_element_* 方法 返回一個WebElement對象
2. find_elements_* 方法 返回WebElement_*對象的列表
3. click() 方法 :點擊頁面
4. send_keys() 方法 : 填寫並提交表單
5. from selenium.webdriver.commom.keys import Keys : 發送特殊鍵
從Web抓取信息