Python採集知網

Python爬蟲初探 selenium+beautifulsoup4+chromedriver

安裝模塊:
* import pymssql
* pip install bs4
* pip install selenium
* pip install pd
* pip install pandas
* pip install PyQt5

安裝瀏覽器驅動:
你自己電腦上裝了什麼瀏覽器,就下載對應的驅動程序即可,本文使用的是Google,所以選擇Google的驅動需要與你的瀏覽器版本對應。
http://chromedriver.storage.googleapis.com/index.html
https://registry.npmmirror.com/binary.html?path=chromedriver
https://www.selenium.dev/selenium/docs/api/py/index.html

配置環境變量:
依次打開我的電腦->屬性->高級系統設置->環境變量,雙擊path,點擊新建,輸入驅動程序chromedriver.exe所在的目錄即可,然後一路點擊確定

@echo off
@title 配置系統環境變量
@echo ******************************************************
@echo 1.Python37_64
@echo 2.Chrome chromedriver.exe
@echo ******************************************************
@echo ===============開始配置系統環境變量=======================

setx PATH=C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64
setx PATH=C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\Scripts
setx PATH=C:\Users\Administrator\AppData\Local\Google\Chrome\Application

@echo ===============配置系統環境變量完成,自動退出=======================
@pause
@exit

簡單驗證一下,新打開一個控制檯,輸入驅動程序文件名,此處爲chromedriver.exe,能夠正常打開即可

**完整的代碼如下:**

from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from lxml.html import etree
import time
import random
import pymssql


user_agent = [
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
"Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
"Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
"Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
"Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
"Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
"Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
"Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10"
]

headers = {
'User-Agent': random.choice(user_agent)
}

topic = "職業技術學院"
url = 'https://kns.cnki.net/kns8/defaultresult/index'
chrome_options = Options()
chrome_options.add_argument('--disable-gpu') # 禁用瀏覽器正在被自動化程序控制的提示
chrome_options.add_argument('--blink-settings=imagesEnabled=false') # 禁止圖片加載
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation']) # 防止被發現
chrome_options.add_experimental_option('excludeSwitches', ['enable-logging']) #禁用顯示 DevTools
browser = Chrome(options=chrome_options,
executable_path=r"C:\Users\Administrator\AppData\Local\Google\Chrome\Application\chromedriver.exe")

browser.maximize_window()

def executeSql(sql):
db=pymssql.connect('127.0.0.1','sa','123456','dbname')
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()

def addDb(tables):
print('addDb',tables)
for index, table in enumerate(tables):
trs=table.xpath('.//tr')
print('trs',trs)
for tr in trs:
item={}
tds= tr.xpath('.//td')
print('trs',tds)
if tds:
for i,td in enumerate(tds):
if i==1:
item["name"]=td.xpath('.//a[1]/text()')[0].replace('\r\n','')
item["link"]=td.xpath('.//a[1]/@href')
if len(item["link"])>0:
item["link"]=item["link"][0]
else:item["link"]=''
elif i==2:
item["author"]=td.xpath('.//a[1]/text()')
if len(item["author"])>0:
item["author"]=item["author"][0].replace('\r\n','')
else:item["author"]=''
elif i==3:
item["source"]=td.xpath('.//a[1]/text()')
if len(item["source"])>0:
item["source"]=item["source"][0].replace('\r\n','')
else:item["source"]=''
elif i==4:
item["date"]=td.xpath('.//text()')
if len(item["date"])>0:
item["date"]=item["date"][0].replace('\r\n','')
else:item["date"]=''
elif i==5:
item["data"]=td.xpath('.//text()')
if len(item["data"])>0:
item["data"]=item["data"][0].replace('\r\n', '')
else:item["data"]=''
elif i==7:
item["download"]=td.xpath('.//a[1]/text()')
if len(item["download"])>0:
item["download"]=item["download"][0].replace('\r\n', '')
else:item["download"]=''
sql = """INSERT INTO [dbo].[KYCG_LunWen_WT]
([wt_Unit],[wt_Type],[wt_Title],[wt_Url],[wt_ResouceType],[wt_Author],[wt_Source],
[wt_Volume],[wt_Content],[wt_DownDate],[wt_Worker],[wt_WorkerName],[wt_WorkerDate])
VALUES('職業技術學院','知網','%s','%s','%s','%s','%s','%s','',getdate(),'admin','admin'
,getdate())""" %(item['name'], item['link'].replace('/KNS8/Detail?', 'https://kns.cnki.net/kcms/detail/detail.aspx?'),item['data'],item["author"],item["source"],item["download"])
print('item',item['name'])
executeSql(sql)

def crawl():
# 請求url
browser.get(url)
browser.implicitly_wait(5)
time.sleep(5)
# 輸入關鍵字
print('輸入關鍵字',topic)
key = browser.find_element_by_id('txt_search')
key.send_keys(topic)
time.sleep(5)
# 搜索
print('搜索關鍵字',topic)
search_btn = browser.find_element_by_class_name('search-btn')
search_btn.click()
time.sleep(5)
# 入庫
print('採集入庫',topic)
divs =browser.find_element_by_xpath('//table[@class="result-table-list"]')
addDb(etree.HTML(divs.get_attribute("outerHTML")))
time.sleep(20)

# 翻頁
print('翻頁採集',topic)
for cp in range(1, 10):
try:
print('翻頁採集',cp)
browser.find_element_by_link_text('下一頁').click()
time.sleep(7)
divs =browser.find_element_by_xpath('//table[@class="result-table-list"]')
addDb(etree.HTML(divs.get_attribute("outerHTML")))
time.sleep(20)
except:
continue

time.sleep(10)
browser.quit()
browser.close()


if __name__ == '__main__':
print('開始採集知網')
crawl()
executeSql("update KYCG_LunWen_WT set wt_Url=replace(wt_Url,'/KNS8/Detail?','https://kns.cnki.net/kcms/detail/detail.aspx?'),wt_Title=replace(wt_Title,' ','') where wt_Type='知網'")

 


[C# 採集知網](https://www.cnblogs.com/luomingui/p/16313288.html)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章