從web抓取信息
urllib模塊 讀取網(wǎng)頁(yè)
>>>import urllib.requset
>>>page = urllib.request.urlopen('http://www.baidu.com')
>>>html = resp.read()
request.urlretrieve 根據(jù)文件的url下載文件
>>>from urllib.request import urlretrieve
>>>from urllib.request import urlopen
>>>from bs4 import BeautifulSoup
>>>html = urlopen("http://www.pythonscraping.com")
>>>bsObj = BeautifulSoup(html)
>>>imageLocation = bsObj.find("a", {"id": "logo"}).find("img")["src"]
>>>urlretrieve (imageLocation, "logo.jpg")
設(shè)置編碼
>>>html = urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)")
>>>bsObj = BeautifulSoup(html)
>>>content = bsObj.find("div", {"id":"mw-content-text"}).get_text()
>>>content = bytes(content, "UTF-8")
>>>content = content.decode("UTF-8")
html.parser模塊提供了HTML分析庫(kù)
webbrowser模塊 在瀏覽器顯示網(wǎng)頁(yè)
>>>import webbrowser
>>>webbrowser.open('http://www.baidu.com') 瀏覽器打開(kāi)百度
requests模塊 從網(wǎng)頁(yè)下載文件
pip install requests
requests.get() 下載一個(gè)網(wǎng)頁(yè)
>>> import requests
>>> res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
>>> type(res)
<class 'requests.models.Response'>
>>> res.status_code == requests.codes.ok 返回狀態(tài)碼
True
>>> len(res.text)
178981
>>> print(res.text[:250])
raise_for_status() 檢查是否下載成功 等同于 res.status_code == requests.codes.ok
>>> res = requests.get('http://inventwithpython.com/page_that_does_not_exist')
>>> res.raise_for_status()
iter_content()方法在循環(huán)的每次迭代中,返回一段內(nèi)容。每一段都是 bytes 數(shù)據(jù)類型,你需要指定一段包含多少字節(jié)。
下載并保存到文件的完整過(guò)程如下:
1.調(diào)用 requests.get()下載該文件。
2.用'wb'調(diào)用 open(),以寫二進(jìn)制的方式打開(kāi)一個(gè)新文件。
3.利用 Respose 對(duì)象的 iter_content()方法做循環(huán)。
4.在每次迭代中調(diào)用 write(),將內(nèi)容寫入該文件。
5.調(diào)用 close()關(guān)閉該文件。
>>> 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()
提交表單
>>> params = {'firstname': 'Ryan', 'lastname': 'Mitchell'}
>>> r = requests.post("http://pythonscraping.com/files/processing.php", data=params)
>>> print(r.text)
提交文件
>>> files = {'uploadFile': open('../files/Python-logo.png', 'rb')}
>>> r = requests.post("http://pythonscraping.com/pages/processing2.php",files=files)
>>> print(r.text)
處理cookie
>>> session = requests.Session()
>>> params = {'username': 'username', 'password': 'password'}
>>> s = session.post("http://pythonscraping.com/pages/cookies/welcome.php", params)
傳遞http請(qǐng)求頭
>>> import requests
>>> from bs4 import BeautifulSoup
>>> session = requests.Session()
>>> headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5)AppleWebKit 537.36 (KHTML, like Gecko) Chrome","Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}
>>> url = "https://www.whatismybrowser.com/developers/what-http-headers-is-my-browser-sending"
>>> req = session.get(url, headers=headers)
>>> bsObj = BeautifulSoup(req.text)
>>> print(bsObj.find("table",{"class":"table-striped"}).get_text)
beautifulSoup模塊 解析HTML
pip install beautifulsoup4
從 HTML 創(chuàng)建一個(gè) BeautifulSoup 對(duì)象
>>> import requests, bs4
>>> res = requests.get('http://nostarch.com')
>>> res.encoding='gb2312' #設(shè)置編碼
>>> res.raise_for_status()
>>> noStarchSoup = bs4.BeautifulSoup(res.text) #bs4.BeautifulSoup(res.text,'html.parser') Windows腳本需要加html.parser參數(shù)
>>> type(noStarchSoup)
>>> exampleFile = open('example.html')
>>> soup = bs4.BeautifulSoup(exampleFile)
>>> type(soup)
>>> print(soup.prettify()) #打印Soup對(duì)象
>>> print(soup.title) #打印title標(biāo)簽
<title>i'm title</title>
>>> print(soup.title.name) #獲取tag名稱
title
>>> soup.title.name = 'mytitle' #修改tag名稱
>>> print(soup.title)
None
>>> print(soup.mytitle)
<title>i'm title</title>
>>> print(soup.p['class'])
myclass
>>> print(soup.p.get'class'))
myclass
>>> print(soup.p.attrs)
{'class': 'myclass'}
>>> soup.p['class']="newclass" #修改class屬性
>>>print(soup.p)
<p><b>The Dormouse's story</b></p>
>>> print(soup.title.string) #獲取tag中的字符串
i'm title
>>> print(soup.title.contents) #將tag子節(jié)點(diǎn)以列表方式輸出
["i'm title"]
.strings 屬性主要應(yīng)用于 tag 中包含多個(gè)字符串,可以進(jìn)行循環(huán)遍歷,示例如下:
for string in soup.strings:
print(repr(string))
.stripped_strings 屬性可以去掉輸出字符串中包含的空格或空行
.parent 屬性來(lái)獲取某個(gè)元素的父節(jié)點(diǎn)
>>> print(soup.h1.parent)
<div>
<h1>主頁(yè)</h1>
</div>
.next_sibling 屬性獲取了該節(jié)點(diǎn)的下一個(gè)兄弟節(jié)點(diǎn),
.previous_sibling 則與之相反,如果節(jié)點(diǎn)不存在,則返回 None。
.next_elements 前節(jié)點(diǎn),不分層次
.previous_elements 后節(jié)點(diǎn)
用 select()方法尋找元素
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('div > span') 所有直接在<div>元素之內(nèi)的<span>元素,中間沒(méi)有其他元素
soup.select("#link1 ~ .sister") 查找 id="link1" 之后 的所有兄弟標(biāo)簽
soup.select("#link1 + .sister") 查找緊跟著 id="link1" 之后 的子標(biāo)簽
soup.select('input[name]') 所有名為<input>,并有一個(gè) name 屬性,其值無(wú)所謂的元素
soup.select('input[type="button"]') 所有名為<input>,并有一個(gè) type 屬性,其值為 button 的元素
>>> import bs4
>>> exampleFile = open('example.html')
>>> exampleSoup = bs4.BeautifulSoup(exampleFile.read())
>>> elems = exampleSoup.select('#author')
>>> type(elems)
<class 'list'>
>>> len(elems)
1
>>> type(elems[0])
<class 'bs4.element.Tag'>
>>> elems[0].getText() 返回匹配元素的文本
'Al Sweigart'
>>> str(elems[0]) 返回匹配元素的字符串,包含html標(biāo)簽
'<span id="author">Al Sweigart</span>'
>>> elems[0].attrs 返回一個(gè)字典
{'id': 'author'}
findAll()
findAll(tag, attributes, recursive, text, limit, keywords)
tag:標(biāo)簽
.findAll('h1')
.findAll(['h1','h2'])
傳入True 匹配任何tag
attributes: 是用一個(gè) Python 字典封裝一個(gè)標(biāo)簽的若干屬性和對(duì)應(yīng)的屬性值
.findAll("span", {"class":{"green", "red"}})
recursive: 設(shè)置為 True , findAll 就會(huì)根據(jù)你的要求去查找標(biāo)簽參數(shù)的所有子標(biāo)簽,以及子標(biāo)簽的子標(biāo)簽。默認(rèn)為True
text:用標(biāo)簽的文本內(nèi)容去匹配,而不是用標(biāo)簽的屬性
.findAll(text=['python','php'])
.findAll('a',text='java')
limit:獲取到匹配的前幾項(xiàng)
.findAll('a',limit=2)
keywords:獲取指定屬性的標(biāo)簽
.findAll(id="text")
.get_text() 返回?zé)o標(biāo)簽文檔
.attrs 獲取標(biāo)簽屬性
.attrs["src"]
find()
find(tag, attributes, recursive, text, keywords)
子標(biāo)簽和后代標(biāo)簽
例如: tr 標(biāo)簽是 tabel 標(biāo)簽的子標(biāo)簽,而 tr 、 th 、 td 、 img 和 span標(biāo)簽都是 tabel 標(biāo)簽的后代標(biāo)簽
.children() 獲取子標(biāo)簽
find("table",{"id":"giftList"}).children
next_siblings()
獲取兄弟標(biāo)簽,處理表格數(shù)據(jù)
bsObj.find("table",{"id":"giftList"}).tr.next_siblings:
previous_sibling()
和next_siblings功能類似,只返回單個(gè)標(biāo)簽
使用正則表達(dá)式
findAll("img",{"src":re.compile("\.\.\/img\/gifts/img.*\.jpg")})
find("div", {"id":"bodyContent"}).findAll("a",href=re.compile("^(/wiki/)((?!:).)*$"))
selenium模塊 控制瀏覽器
pip install selenium
PhantomJS(后臺(tái)運(yùn)行瀏覽器,高版本selenium已經(jīng)不支持) Firefox Chrome
Chrome無(wú)頭
>>> from selenium import webdriver
>>> from selenium.webdriver.chrome.options import Options
>>> chrome_options = Options()
>>> chrome_options.add_argument('--headless')
>>> chrome_options.add_argument('--disable-gpu')
>>>chrome_options.add_argument('--no-sandbox')
>>>browser = webdriver.Chrome(chrome_options=chrome_options)
在centos7中安裝chrome
安裝最新版chrome
#yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
#cat /etc/yum.repos.d/google-chrome.repo
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/x86_64
enabled=1a
gpgcheck=1
gpgkey=https://dl.google.com/linux/linux_signing_key.pub
根據(jù)chrome版本下載對(duì)應(yīng)的chromedriver
# google-chrome --version
https://npm.taobao.org/mirrors/chromedriver/
導(dǎo)入模塊,
>>>from selenium import webdriver
>>>chrome = webdriver.Chrome() #先下載chromedriver 到Python安裝目錄https://sites.google.com/a/chromium.org/chromedriver/downloads
>>>chrome.get('http://www.baidu.com') #打開(kāi)網(wǎng)址
>>>chrome.title #獲取打開(kāi)網(wǎng)址的名稱
>>>chrome.current_url #獲取打開(kāi)網(wǎng)址的url
在頁(yè)面中尋找元素
find_element_*() 返回一個(gè) WebElement 對(duì)象,代表頁(yè)面中匹配查詢的第一個(gè)元素
find_elements_*() 返回 WebElement_*對(duì)象的列表,包含頁(yè)面中所有匹配的元素。
selenium 的 WebDriver 方法,用于尋找元素
browser.find_element_by_class_name(name) 使用 CSS 類 name 的元素
browser.find_elements_by_class_name(name)
browser.find_element_by_css_selector(selector) 匹配 CSS selector 的元素
browser.find_elements_by_css_selector(selector)
browser.find_element_by_id(id) 匹配 id 屬性值的元素
browser.find_elements_by_id(id)
browser.find_element_by_link_text(text) 完全匹配提供的 text 的<a>元素
browser.find_elements_by_link_text(text)
browser.find_element_by_partial_link_text(text) 包含提供的 text 的<a>元素
browser.find_elements_by_partial_link_text(text)
browser.find_element_by_name(name) 匹配 name 屬性值的元素
browser.find_elements_by_name(name)
browser.find_element_by_tag_name(name) 匹配標(biāo)簽 name 的元素
browser.find_elements_by_tag_name(name) (大小寫無(wú)關(guān),<a>元素匹配'a'和'A')
WebElement 的屬性和方法
tag_name 標(biāo)簽名,例如 'a'表示<a>元素
get_attribute(name) 該元素 name 屬性的值
text 該元素內(nèi)的文本,例如<span>hello</span>中的'hello'
clear() 對(duì)于文本字段或文本區(qū)域元素,清除其中輸入的文本
is_displayed() 如果該元素可見(jiàn),返回 True,否則返回 False
is_enabled() 對(duì)于輸入元素,如果該元素啟用,返回 True,否則返回 False
is_selected() 對(duì)于復(fù)選框或單選框元素,如果該元素被選中,選擇 True,否則返回 False
location 一個(gè)字典,包含鍵'x'和'y',表示該元素在頁(yè)面上的位置
page_source 返回頁(yè)面源代碼字符串
click() 模擬鼠標(biāo)點(diǎn)擊該元素
send_keys() 向文本框發(fā)送鍵盤擊鍵
submit() 點(diǎn)擊表單submit按鈕
back() 點(diǎn)擊“返回”按鈕
forward() 點(diǎn)擊“前進(jìn)”按鈕
refresh() 點(diǎn)擊“刷新”按鈕
quit() 點(diǎn)擊“關(guān)閉窗口”按鈕
發(fā)送特殊鍵
from selenium.webdriver.common.keys import Keys
Keys.DOWN, Keys.UP, Keys.LEFT,Keys.RIGHT 鍵盤箭頭鍵
Keys.ENTER, Keys.RETURN 回車和換行鍵
Keys.HOME, Keys.END,Keys.PAGE_DOWN,Keys.PAGE_UP Home 鍵、End 鍵、PageUp 鍵和 Page Down 鍵
Keys.ESCAPE, Keys.BACK_SPACE,Keys.DELETE Esc、 Backspace 和字母鍵
Keys.F1, Keys.F2, . . . , Keys.F12 鍵盤頂部的 F 1 到 F 12 鍵
Keys.TAB Tab 鍵
如果光標(biāo)當(dāng)前不在文本字段中,按下 home 和 end 鍵,將使瀏覽器滾動(dòng)到頁(yè)面的頂部或底部。
>>> from selenium import webdriver
>>> from selenium.webdriver.common.keys import Keys
>>> browser = webdriver.Firefox()
>>> browser.get('http://nostarch.com')
>>> htmlElem = browser.find_element_by_tag_name('html')
>>> htmlElem.send_keys(Keys.END) # scrolls to bottom
>>> htmlElem.send_keys(Keys.HOME) # scrolls to top
獲取cookie
>>>from selenium import webdriver
>>>driver = webdriver.PhantomJS(executable_path='<Path to Phantom JS>')
>>>driver.get("http://pythonscraping.com")
>>>driver.implicitly_wait(1)
>>>print(driver.get_cookies())
pymysql 模塊
鏈接數(shù)據(jù)庫(kù)
>>>conn=pymysql.connect(host='127.0.0.1',user='test',passwd='123456',db='testdb',charset='utf8')
>>> cur=conn.cursor()
>>> cur.execute('select version()')
>>> print(cur.fetchone())
('5.7.24-log',)
>>>sql = "insert into test(title) values ('%s')"% (title)
>>>cur.execute(sql)
>>>cur.connection.commit()
>>> cur.close()
>>> conn.close()
cursor() 創(chuàng)建光標(biāo)對(duì)象
fetchone() 獲取單條數(shù)據(jù)
fetchall() 獲取全部返回?cái)?shù)據(jù)
PySocks 模塊
代理服務(wù)器通信模塊
tesserocr 模塊
識(shí)別驗(yàn)證碼
>>>import tesserocr
>>>from PIL import Image
>>>image = Image.open('code.jpg')
>>>result = tesserocr.imgage_to_text(image)
>>>print(result)