python3爬蟲筆記

2019年6月5日11:48:17 發表評論 3,741 ℃

從web抓取信息

urllib模塊 讀取網頁

>>>import urllib.requset

>>>page = urllib.request.urlopen('http://www.baidu.com')

>>>html = resp.read()

 

request.urlretrieve 根據文件的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")

設置編碼

>>>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分析庫

 

webbrowser模塊 在瀏覽器顯示網頁

>>>import webbrowser

>>>webbrowser.open('http://www.baidu.com') 瀏覽器打開百度

 

requests模塊 從網頁下載文件

pip install requests

requests.get() 下載一個網頁

>>> 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 返回狀態碼

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()方法在循環的每次迭代中,返回一段內容。每一段都是 bytes 數據類型,你需要指定一段包含多少字節。

 

下載并保存到文件的完整過程如下:

1.調用 requests.get()下載該文件。

2.用'wb'調用 open(),以寫二進制的方式打開一個新文件。

3.利用 Respose 對象的 iter_content()方法做循環。

4.在每次迭代中調用 write(),將內容寫入該文件。

5.調用 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()

提交表單

>>> 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請求頭

>>> 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 創建一個 BeautifulSoup 對象

>>> import requests, bs4

>>> res = requests.get('http://nostarch.com')

>>> res.encoding='gb2312' #設置編碼

>>> res.raise_for_status()

>>> noStarchSoup = bs4.BeautifulSoup(res.text) #bs4.BeautifulSoup(res.text,'html.parser') Windows腳本需要加html.parser參數

>>> type(noStarchSoup)

 

>>> exampleFile = open('example.html')

>>> soup = bs4.BeautifulSoup(exampleFile)

>>> type(soup)

>>> print(soup.prettify()) #打印Soup對象

>>> print(soup.title) #打印title標簽

<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子節點以列表方式輸出

["i'm title"]

 

.strings 屬性主要應用于 tag 中包含多個字符串,可以進行循環遍歷,示例如下:

for string in soup.strings:

print(repr(string))

.stripped_strings 屬性可以去掉輸出字符串中包含的空格或空行

 

.parent 屬性來獲取某個元素的父節點

>>> print(soup.h1.parent)

<div>

<h1>主頁</h1>

</div>

 

.next_sibling 屬性獲取了該節點的下一個兄弟節點,

.previous_sibling 則與之相反,如果節點不存在,則返回 None。

 

.next_elements 前節點,不分層次

.previous_elements 后節點

 

select()方法尋找元素

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

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

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

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

soup.select('div > span') 所有直接在<div>元素之內的<span>元素,中間沒有其他元素

soup.select("#link1 ~ .sister") 查找 id="link1" 之后 的所有兄弟標簽

soup.select("#link1 + .sister") 查找緊跟著 id="link1" 之后 的子標簽

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

soup.select('input[type="button"]') 所有名為<input>,并有一個 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標簽

'<span id="author">Al Sweigart</span>'

>>> elems[0].attrs 返回一個字典

{'id': 'author'}

 

findAll()

findAll(tag, attributes, recursive, text, limit, keywords)

tag:標簽

.findAll('h1')

.findAll(['h1','h2'])

傳入True 匹配任何tag

attributes: 是用一個 Python 字典封裝一個標簽的若干屬性和對應的屬性值

.findAll("span", {"class":{"green", "red"}})

recursive: 設置為 True , findAll 就會根據你的要求去查找標簽參數的所有子標簽,以及子標簽的子標簽。默認為True

text:用標簽的文本內容去匹配,而不是用標簽的屬性

.findAll(text=['python','php'])

.findAll('a',text='java')

limit:獲取到匹配的前幾項

.findAll('a',limit=2)

keywords:獲取指定屬性的標簽

.findAll(id="text")

.get_text() 返回無標簽文檔

.attrs 獲取標簽屬性

.attrs["src"]

 

find()

find(tag, attributes, recursive, text, keywords)

 

子標簽和后代標簽

例如: tr 標簽是 tabel 標簽的子標簽,而 tr 、 th 、 td 、 img 和 span標簽都是 tabel 標簽的后代標簽

.children() 獲取子標簽

find("table",{"id":"giftList"}).children

 

next_siblings()

獲取兄弟標簽,處理表格數據

bsObj.find("table",{"id":"giftList"}).tr.next_siblings:

previous_sibling()

和next_siblings功能類似,只返回單個標簽

 

使用正則表達式

findAll("img",{"src":re.compile("\.\.\/img\/gifts/img.*\.jpg")})

find("div", {"id":"bodyContent"}).findAll("a",href=re.compile("^(/wiki/)((?!:).)*$"))

python3爬蟲筆記

 

selenium模塊 控制瀏覽器

pip install selenium

PhantomJS(后臺運行瀏覽器,高版本selenium已經不支持) Firefox Chrome

Chrome無頭

>>> 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

 

根據chrome版本下載對應的chromedriver

# google-chrome --version

https://npm.taobao.org/mirrors/chromedriver/

 

導入模塊,

>>>from selenium import webdriver

>>>chrome = webdriver.Chrome() #先下載chromedriver 到Python安裝目錄https://sites.google.com/a/chromium.org/chromedriver/downloads

>>>chrome.get('http://www.baidu.com') #打開網址

>>>chrome.title #獲取打開網址的名稱

>>>chrome.current_url #獲取打開網址的url

 

在頁面中尋找元素

find_element_*() 返回一個 WebElement 對象,代表頁面中匹配查詢的第一個元素

find_elements_*() 返回 WebElement_*對象的列表,包含頁面中所有匹配的元素。

 

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) 匹配標簽 name 的元素

browser.find_elements_by_tag_name(name) (大小寫無關,<a>元素匹配'a'和'A')

 

WebElement 的屬性和方法

tag_name 標簽名,例如 'a'表示<a>元素

get_attribute(name) 該元素 name 屬性的值

text 該元素內的文本,例如<span>hello</span>中的'hello'

clear() 對于文本字段或文本區域元素,清除其中輸入的文本

is_displayed() 如果該元素可見,返回 True,否則返回 False

is_enabled() 對于輸入元素,如果該元素啟用,返回 True,否則返回 False

is_selected() 對于復選框或單選框元素,如果該元素被選中,選擇 True,否則返回 False

location 一個字典,包含鍵'x'和'y',表示該元素在頁面上的位置

page_source 返回頁面源代碼字符串

 

click() 模擬鼠標點擊該元素

send_keys() 向文本框發送鍵盤擊鍵

submit() 點擊表單submit按鈕

back() 點擊“返回”按鈕

forward() 點擊“前進”按鈕

refresh() 點擊“刷新”按鈕

quit() 點擊“關閉窗口”按鈕

 

發送特殊鍵

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 鍵

 

如果光標當前不在文本字段中,按下 home 和 end 鍵,將使瀏覽器滾動到頁面的頂部或底部。

>>> 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 模塊

鏈接數據庫

>>>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() 創建光標對象

fetchone() 獲取單條數據

fetchall() 獲取全部返回數據

 

PySocks 模塊

代理服務器通信模塊

 

tesserocr 模塊

識別驗證碼

>>>import tesserocr

>>>from PIL import Image

>>>image = Image.open('code.jpg')

>>>result = tesserocr.imgage_to_text(image)

>>>print(result)

【騰訊云】云服務器、云數據庫、COS、CDN、短信等云產品特惠熱賣中

發表評論

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: