使用python的urllib來抓取網(wǎng)頁很容易被當(dāng)作爬蟲來對(duì)待
下面是一個(gè)使用urllib的例子:
import urllib.request
url = 'http://www.itdecent.cn/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自動(dòng)控制chrome等瀏覽器抓取網(wǎng)頁數(shù)據(jù),使用以上方式抓取網(wǎng)頁內(nèi)容的,還可以讓瀏覽器動(dòng)態(tài)的加載網(wǎng)頁內(nèi)容,這方便了抓取使用ajax動(dòng)態(tài)加載的網(wǎng)頁
代碼要點(diǎn):
- 使用
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)頁標(biāo)簽,通過BeautifulSoup初始化一個(gè)bsObj對(duì)象之后,可以使用find、find_all查找網(wǎng)頁標(biāo)簽,查找到的標(biāo)簽還是繼續(xù)使用find、find_all方法
bsObj = BeautifulSoup(html, "html.parser")
note_list = bsObj.find("ul", {"class": "note-list"})
article_list = note_list.find_all("li")
- 如何獲得某個(gè)標(biāo)簽中的屬性,如獲得
<a />中的href屬性
href = i.find('a', {"class": "title"})['href']
- 如何獲得標(biāo)簽中夾雜的文本,如
<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.itdecent.cn/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.itdecent.cn'+article['href'])
time.sleep(0.2)
except Exception as e:
continue
browser.quit()
chrome driver與chrome
這里是chrome driver的下載地址,如果速度太慢,建議使用vpn打開
chrome driver與chrome之間的對(duì)應(yīng)關(guān)系,可以查看各個(gè)版本下面的notes.txt文件,如這里
下載好chrome driver之后將chromedrive.exe文件放在谷歌瀏覽器中chrome.exe的同級(jí)目錄下,接下來就可以使用selenium調(diào)用driver

部分對(duì)應(yīng)關(guān)系.png