使用python
的urllib
來抓取網(wǎng)頁很容易被當作爬蟲來對待
下面是一個使用urllib
的例子:
import urllib.request
url = 'http://www.reibang.com/p/99747a2f29f7'
headers = {
'Connection': 'Keep-Alive',
'Accept': 'text/html, application/xhtml+xml, */*',
'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'
}
req = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(req)
html = response.read().decode()
print(html)
使用selenium
為了防止這種情況下愈,我們可以使用selenium
自動控制chrome
等瀏覽器抓取網(wǎng)頁數(shù)據(jù)宁玫,使用以上方式抓取網(wǎng)頁內(nèi)容的,還可以讓瀏覽器動態(tài)的加載網(wǎng)頁內(nèi)容,這方便了抓取使用ajax
動態(tài)加載的網(wǎng)頁
代碼要點:
- 使用
webdriver
調(diào)用chrome driver
抵屿,C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe
是chrome driver
的安裝路徑
browser = webdriver.Chrome('C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe')
- 獲取到網(wǎng)頁的html代碼之后豁延,可以使用
BeautifulSoup
查找網(wǎng)頁標簽,通過BeautifulSoup
初始化一個bsObj
對象之后惯殊,可以使用find
、find_all
查找網(wǎng)頁標簽也殖,查找到的標簽還是繼續(xù)使用find
土思、find_all
方法
bsObj = BeautifulSoup(html, "html.parser")
note_list = bsObj.find("ul", {"class": "note-list"})
article_list = note_list.find_all("li")
- 如何獲得某個標簽中的屬性,如獲得
<a />
中的href
屬性
href = i.find('a', {"class": "title"})['href']
- 如何獲得標簽中夾雜的文本忆嗜,如
<p> 文本內(nèi)容 </p>
己儒,可以使用get_text
方法
times = i.find('div', {"class": "meta"}).a.get_text()
下面是完整代碼:
from selenium import webdriver
from bs4 import BeautifulSoup
import time
def get_all_article(uid):
tar_url = 'http://www.reibang.com/u/' + uid
browser.get(tar_url)
html = browser.page_source
bsObj = BeautifulSoup(html, "html.parser")
note_list = bsObj.find("ul", {"class": "note-list"})
article_list = note_list.find_all("li")
all_article = []
for i in article_list:
href = i.find('a', {"class": "title"})['href']
times = i.find('div', {"class": "meta"}).a.get_text().strip('\n').strip()
all_article.append({'href': href, 'times': times})
return all_article
browser = webdriver.Chrome('C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe')
browser.set_page_load_timeout(5)
uid = '55672ec82fcd'
all_article = get_all_article(uid=uid)
for article in all_article:
times = int(article['times'])
if times < 10:
for j in range(10-times):
try:
browser.get('http://www.reibang.com'+article['href'])
time.sleep(0.2)
except Exception as e:
continue
browser.quit()
chrome driver與chrome
這里是chrome driver的下載地址,如果速度太慢捆毫,建議使用vpn打開
chrome driver
與chrome
之間的對應(yīng)關(guān)系闪湾,可以查看各個版本下面的notes.txt
文件,如這里
下載好chrome driver
之后將chromedrive.exe
文件放在谷歌瀏覽器中chrome.exe
的同級目錄下绩卤,接下來就可以使用selenium
調(diào)用driver
部分對應(yīng)關(guān)系.png