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)