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)

Python采集知网的更多相关文章

  1. Python开源爬虫项目代码:抓取淘宝、京东、QQ、知网数据--转

    数据来源:数据挖掘入门与实战  公众号: datadw scrapy_jingdong[9]- 京东爬虫.基于scrapy的京东网站爬虫,保存格式为csv.[9]: https://github.co ...

  2. Python爬取中国知网文献、参考文献、引证文献

    前两天老师派了个活,让下载知网上根据高级搜索得到的来源文献的参考文献及引证文献数据,网上找了一些相关博客,感觉都不太合适,因此特此记录,希望对需要的人有帮助. 切入正题,先说这次需求,高级搜索,根据中 ...

  3. 使用selenium模拟知网登录

    之前都是用phantomjs和selenium模拟浏览器动作的,后来phantomjs不再更新,就转用chrome了 本次模拟登录的网站是中国知网http://login.cnki.net/login ...

  4. 中国知网cnki(永久会员账号)

    中国知网cnki(永久会员账号)大男孩免费分享   网站简介: (中国知网http://www.cnki.net/)中国知网是国家知识基础设施(National Knowledge Infrastru ...

  5. 论文 查重 知网 万方 paperpass

    相信各个即将毕业的学生或在岗需要评职称.发论文的职场人士,论文检测都是必不可少的一道程序.面对市场上五花八门的检测软件,到底该如何选择?选择查重后到底该如何修改?现在就做一个知识的普及.其中对于中国的 ...

  6. 2015年最新中国知网CNKI免费账号直接入口

    以下是Free9免费资源网小编收集整理的2015年最新中国知网CNKI免费账号直接入口,现免费分享给大家(仅供测试使用),此类文献数据库资源有时效性,希望对您的学习.工作上有所帮助! 中国知网直接入口 ...

  7. 如何将中国知网CNKI中的文献导入EndNote X6

    如何将中国知网CNKI中的文献导入EndNote X6 下面给出具体步骤: 1.在CNKI中检索目标文献,如检索<基于Qt的三维可视化技术研究> 我喜欢在CNKI(http://www.c ...

  8. 去掉cajviewer 右上角的“中国知网数字出版物超市

    cajviewer软件是一款可以提取pdf字码的软件(即使pdf是扫描版的) 下面是转的一个博文可以去除软件右上角图标的方法: 去掉cajviewer 7.1.2右上角的“中国知网数字出版物超市” 1 ...

  9. Python教程百度网盘哪里有?

    Python为我们提供了非常完善的基础代码库,覆盖了网络.文件.GUI.数据库.文本等大量内容,被形象地称作"内置电池(batteries included)".带你快速入门的Py ...

  10. 如何将知网下载的caj文件转换为pdf文件

    一.问题描述: 最近在知网搜索论文的时候,经常遇到有的论文没有pdf文件的情况,但不得不吐槽我觉得知网做的阅读器确实是有点烂.所以想将caj文件转化为pdf文件,找到了一个比较好的方法,所以希望记录一 ...

随机推荐

  1. 使用JMeter从JSON响应的URL参数中提取特定值

    在使用Apache JMeter进行API测试时,我们经常需要从JSON格式的响应中提取特定字段的值.这可以通过使用JMeter内置的JSON提取器和正则表达式提取器来完成.以下是一个具体的例子,展示 ...

  2. 《.NET内存管理宝典 》(Pro .NET Memory Management) 阅读指南 - 第8章

    本章勘误: 暂无,等待细心的你告诉我哦. 本章注解: 暂无 本章释疑: 暂无,等待你的提问 致谢: MVP 林德熙 MVP 吕毅 sPhinX 相关链接 试读记录

  3. Docker理论

    一.什么是Dcoker 相信docker是什么大家都已经比较清楚了,网上有很详细的介绍,我这里只是大概描述一下. Docker是一个开源的引擎,可以轻松的为任何应用创建一个轻量级的.可移植的.自给自足 ...

  4. 百度文库内容复制 C# webbrowser+Nsoup

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  5. FBNet/FBNetV2/FBNetV3:Facebook在NAS领域的轻量级网络探索 | 轻量级网络

    FBNet系列是完全基于NAS方法的轻量级网络系列,分析当前搜索方法的缺点,逐步增加创新性改进,FBNet结合了DNAS和资源约束,FBNetV2加入了channel和输入分辨率的搜索,FBNetV3 ...

  6. Log4Net使用示例

    <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSe ...

  7. C++ 数学函数、头文件及布尔类型详解

    C++ 数学 C++ 有许多函数可以让您在数字上执行数学任务. 最大值和最小值 max(x, y) 函数可用于找到 x 和 y 的最大值: 示例 cout << max(5, 10); 而 ...

  8. SQL FOREIGN KEY 约束- 保障表之间关系完整性的关键规则

    SQL FOREIGN KEY 约束 SQL FOREIGN KEY 约束用于防止破坏表之间关系的操作.FOREIGN KEY 是一张表中的字段(或字段集合),它引用另一张表中的主键.具有外键的表称为 ...

  9. 华为终端云服务牵手Likee,助力其用户与变现双增长

    如今,社交媒体越来越深入人们的生活,改变了人们沟通方式的同时,也塑造着全新的人际关系和品牌形象.为了迎合用户多样化的需求和提升用户体验, 社交媒体行业的新老企业不断追逐着新技术和新功能.据调查机构Da ...

  10. std::thread 四:异步(async)

    *:如果 std::async 中传递参数 std::lunnch::deferred ,就需要等待调用 get() 或者 wait() 才会执行,并且代码非子线程运行,而是在主线程中执行 #incl ...