通过selenium方式简单爬取京东搜索信息
selenium 反爬虫高级用法

文章标题:探秘:Selenium 反爬虫高级用法一、引言在当今信息爆炸的时代,网络信息获取已经成为人们日常生活和工作中不可或缺的一部分。
然而,随之而来的反爬虫技术也日益复杂与普及。
针对这一问题,Selenium作为广受欢迎的自动化测试工具,也被越来越多的人使用于网络爬虫的应用中,而且针对反爬虫技术的应对也显得尤为重要。
二、Selenium 的基本用法回顾让我们回顾一下Selenium的基本用法。
Selenium是一个自动化测试工具,它可以模拟用户在浏览器上的操作,比如点击按钮、输入文本等,这使得它在网络爬虫中的应用非常广泛。
Selenium还支持多种浏览器,如Chrome、Firefox、Edge等,这为用户提供了更多的选择空间。
三、Selenium 反爬虫高级用法的探讨1. 动态加载页面的处理动态加载页面是当前全球信息湾常见的一种反爬虫手段。
Selenium可以通过模拟用户的操作,等待页面元素加载完成后再进行操作,从而有效应对动态加载页面的反爬虫技术。
2. 验证码的处理验证码是全球信息湾常用的反爬虫手段之一。
Selenium可以通过自动识别验证码的方式,进一步提高爬虫的成功率。
也可以通过模拟鼠标操作,来应对一些需要滑动验证的全球信息湾。
3. 请求头和IP的伪装为了防止被识别出为爬虫,Selenium还可以定制请求头和IP,让全球信息湾认为是一个普通的用户在访问,从而避免被封禁。
四、个人观点和理解在我看来,Selenium作为一款强大的自动化测试工具,其在反爬虫中的应用势必会越来越广泛。
而针对反爬虫技术的不断升级,我们也需要不断探索和学习,以更好地应对各种挑战。
五、总结通过本文的探讨,我们不仅对Selenium的基本用法进行了回顾,还深入探讨了其在反爬虫领域的高级用法。
在未来的网络爬虫应用中,我相信Selenium会发挥越来越重要的作用,成为我们应对反爬虫技术的得力助手。
六、结语在不断发展和创新的信息时代,网络爬虫技术必将发展得更加成熟和多样化。
使用selenium用ISBN在京东上批量爬取书籍信息

使⽤selenium⽤ISBN在京东上批量爬取书籍信息⾸先读取 .xls ⽂件,然后根据表格⾥的ISBN在京东上挨个搜索,再把需要的信息从⽹页上提取出来保存在另⼀个⽂件⾥。
每次运⾏ .py ⽂件后打开浏览器会弹出登录页⾯(30s),在此期间⼿动登录,30秒后开始爬取。
#!/usr/bin/python# -*- coding: UTF-8 -*-from selenium import webdriverfrom mon.exceptions import TimeoutException, NoSuchElementExceptionimport jsonfrom mon.keys import Keysfrom lxml import etreeimport xlrdimport xlwtimport datetimefrom time import sleep# options = webdriver.ChromeOptions()# options.add_argument('--headless')# options.add_argument('--no-sandbox')# options.add_argument('--disable-gpu')# options.add_argument('--disable-dev-shm-usage')# driver = webdriver.Chrome(chrome_options=options)data_dict = tDict = {'ISBN': '0000000000000', '出版时间': '0000-00-00', '版次': '1'}driver = webdriver.Chrome()def test01_login():driver = webdriver.Chrome()driver.get("https:///new/login.aspx?ReturnUrl=https%3A%2F%%2F")sleep(30) # ⼿动登陆⼀次cookies = driver.get_cookies()# 将 cookies 写⼊⽂件with open("cookies.txt", "w") as f:json.dump(cookies, f)def singleData(para):try:driver.get('https:///')# 加载 cookies信息with open("cookies.txt", "r") as f:cookies = json.load(f)for cookie in cookies:driver.add_cookie(cookie)driver.find_element_by_id("key").send_keys(para)driver.find_element_by_xpath('//*[@id="search"]/div/div[2]/button/i').click()sleep(3)html = driver.page_sourceh = etree.HTML(html)# 在搜索到的结果中仅取⼀条链接driver.get("https:" + h.xpath('//*[@id="J_goodsList"]/ul/li[1]/div/div[1]/a/@href')[0])html = driver.page_sourceh = etree.HTML(html)# 获得所爬信息list = h.xpath('//div/ul[@class="parameter2 p-parameter-list"]/li/text()')for li in list:if li.lstrip().startswith('ISBN'): # 消去左边的空格,然后检测以“ISBN”开头的⼀条data_dict["ISBN"] = liif li.lstrip().startswith('出版时间'):data_dict["出版时间"] = liif li.lstrip().startswith('版次'):data_dict["版次"] = li# driver.close()return data_dictexcept Exception as e:# error occurred, log 'e', etc.with open("exception.txt", "a", encoding="utf-8") as f:f.write(str(e) + "\n")f.close()readbook = xlrd.open_workbook(r'table.xls')SheetOfInput = readbook.sheet_by_name('Sheet1')nrows = SheetOfInput.nrows # 获取最⼤⾏writebook = xlwt.Workbook(encoding="utf8") # 打开⼀个excelSheetOfOutput = writebook.add_sheet('test') # 在打开的excel中添加⼀个sheettest01_login()for gi in range(0,nrows):try:lng = SheetOfInput.cell(gi, 4).value # 获取i⾏3列的表格值tDict = singleData(lng)SheetOfOutput.write(gi, 0, tDict["ISBN"])SheetOfOutput.write(gi, 1, tDict["出版时间"])SheetOfOutput.write(gi, 2, tDict["版次"])writebook.save('answer.xls')print('tDict["ISBN"] = %s, tDict["出版时间"] = %s, tDict["版次"] = %s, gi = %d. ' %(tDict["ISBN"], tDict["出版时间"], tDict["版次"], gi)) except Exception as e:# error occurred, log 'e', etc.with open("exception.txt", "a", encoding="utf-8") as f:f.write(str(e) + "\n")f.close()driver.quit()######################################## 定义⼀个爬⾍函数,针对单条isbn进⾏爬取,返回⼀个字典# 打开table,读取isbn号,# 调⽤定义的函数,然后将返回的字典写⼊table。
atstation selenium爬取方案

atstation selenium爬取方案
ATStation Selenium爬取方案是一种使用Selenium WebDriver 进行网页爬取的方案。
Selenium WebDriver是一个用于自动化网页测试的工具,可以模拟真实用户操作,如点击、输入等,从而实现对网页的爬取。
以下是ATStation Selenium爬取方案的一般步骤:
1.安装Selenium和相关工具:首先需要安装Selenium以及对应的WebDriver,例如ChromeDriver或FirefoxDriver。
这些工具可以通过官方网站或相关资源站点下载。
2.初始化Selenium驱动程序:在Python代码中导入Selenium 模块,并创建一个WebDriver对象。
这个对象可以被认为是我们的浏览器。
3.打开目标网页:使用WebDriver对象的get方法打开目标网页。
4.定位元素:使用Selenium提供的定位方法,如id、name、class name、tag name、link text、partial link text、xpath、css selector等,定位到需要爬取的元素。
5.爬取数据:对定位到的元素进行操作,如点击、输入等,获取需要的数据。
6.关闭浏览器:完成数据爬取后,关闭浏览器。
需要注意的是,使用Selenium进行网页爬取时,应遵守网站的使用规则,避免对网站造成过大的负担或违反相关法律法规。
此
外,由于Selenium会模拟真实用户操作,因此可能会被网站识别为机器人行为,需要进行相应的处理。
python3selenium抓取网页多个表格数据,并导入execl中

python3selenium抓取⽹页多个表格数据,并导⼊execl中1. ⾸先我需要抓取数据的⽹址是:'https:///data/mobile/device'2. 打开浏览器,输⼊⽹址,是这个页⾯3. 我想要抓取,品牌,机型,系统,分辨率,联⽹右边的表格4. 使⽤ pycharm IDE,下载 selenium模块pip install selenium(请在python安装时勾选pip)5. 代码如下1. #!/usr/bin/env python2. # -*- coding: UTF-8 -*-3. from selenium import webdriver4. from selenium.webdriver.chrome.options import Options5. import time6. import openpyxl7. import sys8. import datetime9. import importlib10. import xlwt11. import xlrd12.13. url = 'https:///data/mobile/device'14.15.16. def wait(class_name):17. for trytimes in range(0, 10):18. # noinspection PyBroadException19. try:20. browser.find_element_by_class_name(class_name).click()21. break22. except Exception:23. time.sleep(0.5)24.25. def waits(class_name):26. for trytimes in range(0, 10):27. # noinspection PyBroadException28. try:29. element = browser.find_elements_by_class_name(class_name)30. break31. except Exception:32. time.sleep(10)33. return element34.35. def save_data(dict):36. fileName = u'百度研究学院移动平台.xls'37.38. # 新建新的Excel⽂档39. wb = xlwt.Workbook(encoding='utf-8')40.41. for d in dict:42. sheet = wb.add_sheet(d, cell_overwrite_ok=True)43. headlist = [d, '占⽐']44. row = 045. col = 046. for head in headlist:47. sheet.write(col, row, head)48. row += 149.50. i = 051. for data in dict[d]:52. if (i % 2 == 0):53. col += 154. sheet.write(col, i % 2, data)55. i += 156. wb.save(fileName)57.58. def wait_refresh():59. try:60. browser.refresh() # 刷新⽅法 refresh61. print ('test pass: refresh successful')62. time.sleep(1)63. except Exception as e:64. print ('Exception found', format(e))65.66. def get_data():67. #保存5个类别的数据,list_button中是class_name68. list_button = ['icon-brand','icon-device', 'icon-os', 'icon-screen','icon-network']69.70. #字典保存所有数据71. icon_brand = []72. icon_device = []73. icon_os = []74. icon_screen = []75. icon_network = []76. dict = {'icon-brand':icon_brand, 'icon-device':icon_device, 'icon-os':icon_os , 'icon-screen':icon_screen , 'icon-network':icon_network }77.78. #分别点击5个按钮,保存数据,品牌,机型,系统分辨率,联⽹79. for button in list_button:80. print('************',button,'********************')81.82. wait(button)83. time.sleep(2)84. element_name = browser.find_elements_by_class_name('dtd1')85. element_rank = browser.find_elements_by_class_name('dtd3')86.87. name_list = []88. rank_list = []89. listen = len(element_name)90.91. for name in element_name:92. print(element_name)93.94. name_list.append(name.get_attribute('textContent'))95.96. #print(name.get_attribute('textContent'))97.98. for rank in element_rank:99. rank_list.append(rank.get_attribute('textContent'))100.101. for i in range(0, listen):102. dict[button].append(name_list[i])103. dict[button].append(rank_list[i])104. print(dict)105. return dict106.107. ######################################################################################108.109. #打开浏览器110. browser = webdriver.Chrome()111.112. #最⼤化窗⼝113. browser.maximize_window()114.115. #输⼊⽹址116. browser.get(url)117.118. #获取数据119. dict_data = get_data()120.121. #写⼊表格122. importlib.reload(sys)123. save_data(dict_data)124.5. ⽣成的表格形式如下。
java爬虫 京东(python爬虫京东)

java爬虫京东(python爬虫京东)随着互联网的普及,越来越多的人开始依赖电子商务平台购买商品。
京东作为国内最大的电商之一,自然成为了很多人的首选。
为了更好地了解京东上的商品信息和价格变化,我们可以使用爬虫技术来实现快速获取数据的目的。
Java是一种广泛使用的编程语言,其生态系统庞大、稳定、安全,因此在爬虫领域也有着不错的表现。
在本文中,我们将使用Java语言来实现京东商品信息的爬取。
首先,我们需要确定需要爬取哪些信息。
在京东上,每个商品都有一个唯一的商品ID,因此我们可以通过访问商品详情页来获取商品的名称、价格、销量、评价等信息。
我们可以通过正则表达式或者第三方库Jsoup来解析HTML页面,获取我们需要的信息。
接下来,我们需要模拟浏览器发送HTTP请求,访问京东网站。
我们可以使用Java中的HttpURLConnection或者第三方库OkHttp来实现。
在发送请求时,我们需要设置User Agent、Referer和Cookie等参数,以模拟浏览器的行为,从而避免被京东的反爬虫机制识别出来。
当我们成功获取了商品信息后,我们可以将其存储到数据库或者文件中,以供后续分析和使用。
在存储时,我们需要考虑数据的去重和更新问题,避免重复爬取和存储过多无用数据。
最后,我们需要考虑爬虫的运行效率和稳定性。
在京东上,商品数量庞大,因此我们需要使用多线程或者分布式爬虫来提高爬取速度。
同时,我们需要设置合理的爬虫间隔时间,避免对服务器造成过大的负担。
此外,我们还需要处理一些异常情况,例如网络连接失败、页面解析错误等,以保证爬虫的稳定性和鲁棒性。
总之,使用Java语言实现京东商品信息的爬取是一项有趣且实用的技术。
通过爬虫技术,我们可以更好地了解京东上的商品信息,为我们的购物提供更多的便利和选择。
当然,在使用爬虫时,我们也需要遵守网络伦理和法律规定,以避免对他人造成不必要的困扰和损失。
《Python网络爬虫技术案例教程》PPT课件(共10单元)十单元项目实战京东商品信息爬取及数据分析

例如,输入“手机”,搜索 京东网站中手机相关的商品信 息(见图10-1),包括不同品 牌不同型号的手机价格、店铺 名和评价数(根据评价数可推 测销量)。通过这些数据可以 分析手机的价格分布、不同型 号手机销量和均价、店铺销量 比例等。
图10-1 京东网站搜索的手机相关商品信息
10.2 爬虫实现
初始化模块
#输入关键字
#调用search函数 #调用goods_parse函数
10.2 爬虫实现
10.2.4 主模块
运行程序后,MongoDB数据库中的内容如图10-5所示。
图10-5 MongoDB数据库中的内容(部分)
10.3 爬虫数据分析
在数据分析方面,Python有非常强大的第三方库,pandas就是其中之一,它是 基于NumPy数组构建的,可以更快更简单地预处理、清洗和分析数据。
例如字符串“¥4999.00”中,将“¥”使用空字符替换;字符串“1.4万+”中 ,将“+”和“.”使用空字符替换,然后将“万”使用“000”替换;字符串“1万 +”中,将“+”使用空字符替换,然后将“万”使用“0000”替换。由于搜索的结 果中包含了价格待发布的手机信息,所以此处筛选出标明价格的数据。
10.3.3 分析数据
(2)分析华为各型号手机的销售量和均价,如mate30、p40、荣耀30、nova7 、畅享20和麦芒9等。由于京东网站只有近6个月商品的评价信息,故此处,将评价数 看作销售量进行分析。首先,根据手机型号筛选数据;然后,统计每个型号手机的销 量和均价;最后,绘制柱状图(x轴表示手机型号,y轴表示该手机销量或均价),并 在每个长条上方标明销量或均价的值。
pandas库不是Python内置的标准库,使用之前需要安装,安装方法与requests 库的安装类似(请参考2.3.2小节),此处不再赘述。
python selenium 爬虫实例
文章标题:深入探讨Python Selenium爬虫实例一、引言在当今互联网时代,数据具有极其重要的意义。
而爬虫作为一种数据获取的工具,被广泛应用于各行各业。
Python Selenium是一种强大的自动化测试工具,同时也可以用来进行网页数据爬取。
本文将深入探讨Python Selenium爬虫实例,帮助读者全面了解其原理和应用。
二、Python Selenium简介Python Selenium是一种自动化测试工具,最初是为全球信息湾测试开发的,但是它的功能远不止于此。
它可以模拟人的操作,实现自动化操作浏览器的功能,比如模拟点击、输入、下拉框选择等。
Python Selenium也可以用于网页数据的爬取。
三、Python Selenium爬虫实例详解1. 安装Python Selenium库我们需要安装Python Selenium库,可以通过pip命令进行安装:```pythonpip install selenium```2. 配置浏览器驱动接下来,需要下载相应浏览器的驱动,比如Chrome浏览器需要下载ChromeDriver。
然后将其添加到环境变量中,或者指定驱动的路径:```pythonfrom selenium import webdriverdriver =webdriver.Chrome(executable_path='path_to_chromedriver') ```3. 编写爬虫代码有了Python Selenium库和浏览器驱动之后,就可以开始编写爬虫代码了。
我们可以使用Selenium打开网页、获取元素、模拟点击等操作,实现网页数据的自动获取和处理。
四、Python Selenium爬虫实例的应用Python Selenium爬虫实例可以应用于各种场景,比如商品信息的抓取、文章的采集、自动化测试等。
它可以大大提高网页数据爬取的效率和灵活性,是一个非常实用的工具。
atstation selenium爬取方案 -回复
atstation selenium爬取方案-回复Selenium爬取方案在网络爬虫的世界中,Selenium是一个强大的工具,它以其自动化浏览器的功能而闻名。
它可以模拟用户与网站的交互,并完成一系列复杂的操作,如点击、填写表单等。
因此,Selenium经常被用来应对那些通过JavaScript生成内容的网站。
在本文中,我们将一步一步地介绍如何使用Selenium来爬取网页内容。
1. 安装Selenium和相关工具首先,我们需要安装Selenium以及Python的Selenium模块。
在终端中执行以下命令:pip install selenium此外,我们还需要一个Web浏览器驱动程序,用于与Selenium进行交互。
根据你所使用的浏览器不同,你可以选择下载合适的驱动程序,如Chrome驱动程序或Firefox驱动程序。
下载完成后,将驱动程序的路径添加到系统环境变量中,这样Selenium才能找到它。
2. 初始化Selenium驱动程序接下来,我们需要初始化Selenium驱动程序,以便使用它来控制浏览器。
首先,导入Selenium模块:pythonfrom selenium import webdriver然后,创建一个WebDriver对象。
这个对象可以被认为是我们的浏览器窗口,我们可以使用它来执行各种操作:pythondriver = webdriver.Chrome() # 如果你安装了Chrome驱动程序3. 打开网页当我们创建了WebDriver对象后,我们可以使用`get()`方法来打开网页。
例如,要打开百度搜索的页面,我们可以执行以下操作:driver.get("这样,浏览器就会自动打开指定的网页。
4. 查找元素要从网页上提取信息,我们首先需要找到相应的元素。
幸运的是,Selenium 提供了许多方法来查找元素,比如根据标签名、类名、CSS选择器等。
以下是一些示例:pythonelement = driver.find_element_by_tag_name("div") # 根据标签名查找元素element = driver.find_element_by_class_name("example") # 根据类名查找元素element = driver.find_element_by_css_selector("#id") # 根据CSS 选择器查找元素一旦找到了元素,我们就可以执行想要的操作,比如点击、获取或设置属5. 执行操作接下来,我们需要执行一些操作,如点击按钮、填写表单等。
爬虫爬取数据的方式和方法
爬虫爬取数据的方式和方法爬虫是一种自动化的程序,用于从互联网上获取数据。
爬虫可以按照一定的规则和算法,自动地访问网页、抓取数据,并将数据存储在本地或数据库中。
以下是一些常见的爬虫爬取数据的方式和方法:1. 基于请求的爬虫这种爬虫通过向目标网站发送请求,获取网页的HTML代码,然后解析HTML代码获取需要的数据。
常见的库有requests、urllib等。
基于请求的爬虫比较简单,适用于小型网站,但对于大型网站、反爬机制严格的网站,这种方式很容易被限制或封禁。
2. 基于浏览器的爬虫这种爬虫使用浏览器自动化工具(如Selenium、Puppeteer等)模拟真实用户操作,打开网页、点击按钮、填写表单等,从而获取数据。
基于浏览器的爬虫能够更好地模拟真实用户行为,不易被目标网站检测到,但同时也更复杂、成本更高。
3. 基于网络爬虫库的爬虫这种爬虫使用一些专门的网络爬虫库(如BeautifulSoup、Scrapy 等)来解析HTML代码、提取数据。
这些库提供了丰富的功能和工具,可以方便地实现各种数据抓取需求。
基于网络爬虫库的爬虫比较灵活、功能强大,但也需要一定的技术基础和经验。
4. 多线程/多进程爬虫这种爬虫使用多线程或多进程技术,同时从多个目标网站抓取数据。
多线程/多进程爬虫能够显著提高数据抓取的效率和速度,但同时也需要处理线程/进程间的同步和通信问题。
常见的库有threading、multiprocessing等。
5. 分布式爬虫分布式爬虫是一种更为强大的数据抓取方式,它将数据抓取任务分散到多个计算机节点上,利用集群计算和分布式存储技术,实现大规模、高效的数据抓取。
常见的框架有Scrapy-Redis、Scrapy-Cluster 等。
分布式爬虫需要解决节点间的通信、任务分配、数据同步等问题,同时还需要考虑数据的安全性和隐私保护问题。
【爬虫】京东商品连接
【爬⾍】京东商品连接# -*- coding: utf-8 -*-from __future__ import divisionfrom selenium import webdriverimport timefrom mon.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECimport requestsfrom threading import Threadfrom pyquery import PyQuery as pqimport chardetimport copyimport xlwtimport osimport mPingimport datetimeimport xlwtfrom xlrd import open_workbooknow_time = time.strftime('%H-%M-%S', time.localtime(time.time()))print now_time# print chardet.detect(now_time)# print chardet.detect(time_now_time)#xls_name = ("京东爬⾍数据.xls").decode("utf-8")xls_name = ("京东爬⾍数据"+str(now_time)+".xls").decode("utf-8")#print type(xls_name)#print "京东爬⾍数据"+str(now_time)+".xls"title = ["链接", "名称", "价格", "晒图", "好评", "中评", "差评", "全部评价"]urllist = ["https:///11936238.html","https:///11841674.html"]URLSource = "京东URL.txt".decode('utf-8')if os.path.isfile(URLSource):print "发现URL⽂件,准备开始爬⾍".decode('utf-8')else:print "亲当前⽬录下的url⽂件: \"".decode('utf-8')+URLSource+"\" 不存在,请添加后再运⾏".decode('utf-8')exit(1)def msleep1():time.sleep(1)def msleep2():print "...2",time.sleep(1)print "...1",time.sleep(1)print "...0"def msleep3():print "5",time.sleep(1)print "...4",time.sleep(1)print "...3",time.sleep(1)print "...2",time.sleep(1)print "...1",time.sleep(1)print "...0"def warnningtext():return"这⾥⽆法正确获取数据(偶尔⽹速问题会影响⼀两个数据),请⼿动检查,如果是代码问题请联系开发修改".decode("utf-8")def cannotgetdataprint(text):print ("⽆法获取"+text+" 请⼿动检查⼀下然后联系开发⼈员").decode('utf-8')def mprint(str):#print "",print "############# " + str.decode('utf-8') + " #############"def debugprint(str):print "", #不换⾏空输出""后⾯加 ,print "debugprint@@@ " + str.decode('utf-8')def totwrite(str):return str.decode('utf-8')# mPing.mNetPing('')# chromeOptions = webdriver.ChromeOptions()# prefs = {"profile.managed_default_content_settings.images":2}# chromeOptions.add_experimental_option("prefs",prefs)# driver = webdriver.Chrome(chrome_options=chromeOptions)prefs = {"profile.managed_default_content_settings.images":2}option = webdriver.ChromeOptions()option.add_argument("test-type")#不显⽰警告option.add_experimental_option("prefs",prefs)#不显⽰图⽚global timesurltimesurl = 1global webdriver_chrome#webdriver_chrome = webdriver.PhantomJS()#phantomjs⽆法加载ajax 所以这⾥不能⽤还是要⽤chrome来模拟动态的加载webdriver_chrome = webdriver.Chrome(chrome_options=option)#webdriver_chrome.set_window_size(2000,2000)def isUrlBefore():pass#打开url后地址是否被跳转如果跳转那就跳过该地址并写⼊警告def isString(isstr, data):if isstr in str(data.encode("utf-8")):return Falsedef openweb(url):global starttimeglobal driver_waitglobal isOffsaleCOUNTINUE = FalseSKIP = 1TIAOZHUAN = 2LOADERROR = 3FATALERROR = 4mprint("努⼒加载链接中,请耐⼼等待")try:try:#获取源码进⾏判断respone = requests.get(url)#正确打开连接isOffsale = False #初始化设置为不下柜if respone.status_code == 200:#正确加载价格页⾯包括下柜的页⾯if"商品评价"in str(respone.text.encode("utf-8")):#说明页⾯正常访问到商品页⾯否则可能被跳转了# print respone.textisOffsale = Falseif"商品已下柜"in str(respone.text.encode("utf-8")):isOffsale = Trueelse:return TIAOZHUAN #说明页⾯不是价格页⾯被跳转了?else:#⽆法打开连接return LOADERROR#状态码不是200说明访问有问题except Exception, e:print Exception, e#⽆法获取源码return FATALERROR#以下代码应该不会被执⾏webdriver_chrome.get(url)# mprint("获取当前地址")if"?c"in getcurrenturl():#有了上⾯的if "商品评价" in判断后这段代码应该不会被执⾏到mprint("地址已经被跳转")return SKIPdriver_wait = WebDriverWait(webdriver_chrome, 10)return COUNTINUEexcept Exception:mprint("请注意,链接有问题⽆法打开程序可能停⽌") print urlprint getcurrenturl()return SKIPfinally:debugprint("打印url")def get_element_bycssselector(css_selector):element = driver_wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, css_selector)))# print element.textreturn elementdef get_datanum_bycssselectorlist(css_selector_list, text):for css_selector in css_selector_list:try:# print css_selectorelement = driver_wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, css_selector)))data_num = element.get_attribute('data-num')if isString(text, element.text):print element.text + ":" + str(data_num) # mprint ("显⽰好评")return data_numelse:mprint("⽆法获取")except:passreturn warnningtext()def get_element_byxpathlist(xpath_list, text):for xpath in xpath_list:try:element = driver_wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))# print element.textif isString(text, element.text):print element.textreturn elementelse:mprint("⽆法获取xpath如下")print xpathexcept:mprint(xpath)passreturn None# def try_element(element):# try:# element# except:# passdef getname():debugprint("start find name btn")try:myname = webdriver_chrome.find_element_by_class_name('sku-name')mprint("1名称:")print myname.textreturn myname.textexcept Exception:passtry:myname = webdriver_chrome.find_element_by_css_selector('#name > h1')mprint("2名称:")#⽣鲜书籍print myname.textreturn myname.textexcept Exception:passtry:mprint("3名称:")#⽣鲜书籍print myname.textreturn myname.textexcept Exception:mprint("第 3次抓取商品名称失败")return warnningtext()def getprice():debugprint("start getprice")try:myprice = driver_wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div.summary.summary-first > div > div.summary-price.J-summary-price > div.dd > span'))) mprint("1价格:")# print myprice.textfinalprice = myprice.text.encode ('utf-8').replace ('¥', '')if finalprice == "":msleep1()finalprice = myprice.text.encode ('utf-8').replace ('¥', '')if finalprice == "":msleep2 ()finalprice = myprice.text.encode ('utf-8').replace ('¥', '')if finalprice == "":msleep3 ()finalprice = myprice.text.encode ('utf-8').replace ('¥', '')print finalpricereturn finalpriceexcept Exception:#估计下架做下架的抓取passtry: # ⽣鲜书籍抓取价格myprice = driver_wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#jd-price"))) # ⽣鲜可⽤# myprice = webdriver_chrome.find_element_by_xpath("/html/body/div[7]/div/div[2]/div[3]/div/div[1]/div[2]/span/span[2]")mprint("2价格:")# print myprice.textfinalprice = myprice.text.encode ('utf-8').replace ('¥', '')if finalprice == "":msleep1 ()finalprice = myprice.text.encode ('utf-8').replace ('¥', '')if finalprice == "":msleep2 ()finalprice = myprice.text.encode ('utf-8').replace ('¥', '')if finalprice == "":msleep3 ()finalprice = myprice.text.encode ('utf-8').replace ('¥', '')print finalpricereturn finalpriceexcept Exception: # 估计下架做下架的抓取passtry: # ⽣鲜书籍抓取价格myprice = driver_wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.summary-price.J-summary-price > div > div.dd > span > span"))) # ⽣鲜可⽤mprint("3价格:")# print myprice.textfinalprice = myprice.text.encode ('utf-8').replace ('¥', '')if finalprice == "":msleep1 ()finalprice = myprice.text.encode ('utf-8').replace ('¥', '')if finalprice == "":msleep2 ()finalprice = myprice.text.encode ('utf-8').replace ('¥', '')if finalprice == "":msleep3 ()finalprice = myprice.text.encode ('utf-8').replace ('¥', '')print finalpricereturn finalpriceexcept Exception: # 估计下架做下架的抓取passtry: # 下架的抓取前⾯判断了下架这⾥基本上不会执⾏了mprint("4下架:")soldout = webdriver_chrome.find_element_by_class_name('itemover-tip') # 抓下柜下架 “该商品已下柜,欢迎挑选其他商品!”print soldout.textreturn soldout.textexcept Exception:mprint("抓不到价格也不是下架请检查")return warnningtext()def scrolldown():debugprint("准备开始滚动500")webdriver_chrome.execute_script("window.scrollBy(0,500)")debugprint("已向下滚动500")def clickcommentbtn():xpath1 = '//*[@id="detail"]/div[1]/ul/li[5]'xpath2 = '//*[@id="detail"]/div[1]/ul/li[4]'# xpath3 = '#comments-list > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li:nth-child(3)'btn = get_element_byxpathlist([xpath1, xpath2], "商品评价")if btn is not None:try:btn.click()# mprint("xpath点击")except Exception, e:mprint("btn⾮空不过点击失败了⼀般不会这样的报错是否是:Element is not clickable at point (697, 299). Other element would receive the click")print Exception, eelse:# pass#其他判断基本上不会到这⾥css_sele1 = '# detail > rge > ul > li:nth-child(4)'css_sele2= '#detail > rge > ul > li.current'try:get_element_bycssselector(css_sele1).click()mprint("通过csssele获取到")print css_sele1except:try:get_element_bycssselector(css_sele2).click()mprint("通过csssele获取到")print css_sele1except:mprint("实在找不到联系开发程序可能终⽌")try:#1#detail > rge > ul > li.current > smysumcommentbtn = webdriver_chrome.find_element_by_xpath ('//*[@id="detail"]/div[1]/ul/li[5]')mprint("1点击")print mysumcommentbtn.text, # 三个按钮的链接要⽤其他的(运动户外类)# mprint("运动户外类?")if"商品评价"in str(mysumcommentbtn.text.encode("utf-8")):mysumcommentbtn.click()mprint("~~~~~~点击了按钮") # 这句有问题return Trueelse:mprint("找不到按钮商品评价继续寻找2")except:passtry:#2mysumcommentbtn = webdriver_chrome.find_element_by_xpath ('//*[@id="detail"]/div[1]/ul/li[4]')mprint("2点击")print mysumcommentbtn.textif"商品评价"in str(mysumcommentbtn.text.encode("utf-8")):mysumcommentbtn.click()mprint("~~~~~~点击了评论总量按钮")return Trueelse:mprint("找到按钮不是商品评价继续寻找3")except:mprint("2点击找不到继续下⼀步")passtry:#3css_sele = '# detail > rge > ul > li:nth-child(4)' # ⾹蕉# http: // / 11461683.htmlmysumcommentbtn = driver_wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_sele)))mprint("3点击")print mysumcommentbtn.textif"商品评价"in str(mysumcommentbtn.text.encode("utf-8")):mysumcommentbtn.click()mprint("~~~~~~点击了评论总量按钮")return Trueexcept:mprint("找不到按钮商品评价继续寻找4 ")passtry:#4css_sele = '#detail-tab-comm' # 书籍类⽐较多mysumcommentbtn = driver_wait.until (EC.element_to_be_clickable ((By.CSS_SELECTOR, css_sele)))mprint("4点击")print mysumcommentbtn.textif"商品评价"in str(mysumcommentbtn.text.encode("utf-8")):mysumcommentbtn.click()mprint("~~~~~~点击了评论总量按钮")return Trueexcept:mprint("找不到按钮商品评价继续寻找5")passtry:#5css_sele = '#detail > rge > ul > li.current' # ⾹蕉书籍# http: // / 11461683.htmlmysumcommentbtn = driver_wait.until (EC.element_to_be_clickable ((By.CSS_SELECTOR, css_sele)))mprint("5点击")print mysumcommentbtn.textif"商品评价"in str(mysumcommentbtn.text.encode("utf-8")):mysumcommentbtn.click()mprint("~~~~~~点击了评论总量按钮")return Trueelse:mprint("第五次也找不到只能⼿动找了")print getcurrenturl()return warnningtext()except:mprint("⽆法找到商品评价按钮请联系开发提供url:")print getcurrenturl()return warnningtext()"""def getshowpicnum():css_sele1 = '#comment > div.mc > ments-list.ETab > div.tab-main.small > ul > li:nth-child(2)' css_sele2 = '#comments-list > div.mt > div > ul > li:nth-child(2)'for i in range(3):#循环查找3次pic_num = get_datanum_bycssselectorlist ([css_sele1, css_sele2], "晒图")if pic_num is not None:# mprint(pic_num)return pic_numelse:# passmprint("shaitu")# print u"第"+str(i+1)+u"次没找到,准备开始第"+str(i+2)+u"次查找""""global data_numglobal myshowpictry:#comments-list > div.mt > div > ul > li:nth-child(2)# comment > div.mc > ments-list.ETab > div.tab-main.small > ul > li:nth-child(2)css_sele = '#comment > div.mc > ments-list.ETab > div.tab-main.small > ul > li:nth-child(2)' myshowpic = driver_wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_sele)))data_num = myshowpic.get_attribute('data-num')mprint("1晒图")print myshowpic.text,if"晒图"in str(myshowpic.text.encode("utf-8")):debugprint("第⼀次判断正确是晒图按钮")if data_num is not None:return data_numelse:mprint("晒图的值没有正确加载 5s后再次验证")msleep3()data_num = myshowpic.get_attribute ('data-num')if data_num is not None:mprint("找到晒图值")print myshowpic.textmprint ("晒图的值没有正确加载 5s后再次验证")msleep3 ()msleep3 ()data_num = myshowpic.get_attribute ('data-num')if data_num is not None:mprint ("找到晒图值")print myshowpic.textreturn data_numelse:#多次查找⽆法找到值mprint("#多次查找⽆法找到值")return warnningtext()else:debugprint("第⼀次判断错误按钮找到不是晒图联系开发提供截图")except:debugprint("第⼀次判断没找到按钮开始第⼆次")try:css_sele = '#comments-list > div.mt > div > ul > li:nth-child(2)'myshowpic = driver_wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_sele)))mprint("2晒图")print myshowpic.textif"晒图"in str(myshowpic.text.encode("utf-8")):debugprint("第2次判断正确是晒图按钮")if myshowpic.get_attribute('data-num') is not None:return myshowpic.get_attribute('data-num')else:mprint ("晒图的值没有正确加载 5s后再次验证")msleep3 ()data_num = myshowpic.get_attribute ('data-num')if data_num is not None:mprint ("找到晒图值")print myshowpic.textreturn data_numelse:mprint ("晒图的值没有正确加载 5s后再次验证")msleep3 ()msleep3 ()data_num = myshowpic.get_attribute ('data-num')if data_num is not None:mprint ("找到晒图值")print myshowpic.textreturn data_numelse: # 多次查找⽆法找到值return warnningtext ()else:debugprint("第2次判断错误按钮找到不是晒图联系开发提供截图")except:debugprint("第2次判断没找到按钮联系开发")return warnningtext()"""def totalcomment():css_sele1 = '#comment > div.mc > ments-list.ETab > div.tab-main.small > ul > li.current'css_sele2 = '#comments-list > div.mt > div > ul > li.ui-switchable-item.trig-item.curr'return get_datanum_bycssselectorlist([css_sele1, css_sele2], "全部评价")"""try:css_sele = '#comment > div.mc > ments-list.ETab > div.tab-main.small > ul > li.current'mypositivecomment = driver_wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_sele)))# mypositivecomment = webdriver_chrome.find_element_by_css_selector("#comments-list > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li:nth-child(3)") data_num = mypositivecomment.get_attribute('data-num')mprint("1全部评价")print mypositivecomment.text, data_numif"全部评价"in str(mypositivecomment.text.encode("utf-8")):debugprint("第1次判断正确是全部评价按钮")if data_num is not None:return data_numelse:mprint("全部评价的值没有正确加载请⼿动查找")return cannotgetdataprint(mypositivecomment.text)else:debugprint("第1次判断错误按钮找到不是全部评价联系开发提供截图")except:debugprint("第⼀次抓全部评价失败继续第⼆次")passtry:css_sele = '#comments-list > div.mt > div > ul > li.ui-switchable-item.trig-item.curr'mypositivecomment = driver_wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_sele)))# mypositivecomment = webdriver_chrome.find_element_by_css_selector("#comments-list > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li:nth-child(3)") data_num = mypositivecomment.get_attribute('data-num')mprint("2全部评价")print mypositivecomment.text, data_numif"全部评价"in str(mypositivecomment.text.encode("utf-8")):debugprint("第2次判断正确是全部评价按钮")if data_num is not None:return data_numelse:mprint("全部评价的值没有正确加载请⼿动查找")return cannotgetdataprint(mypositivecomment.text)else:debugprint("第2次判断错误按钮找到不是全部评价联系开发提供截图")except:debugprint("第2次抓全部评价失败继续第⼆次")return cannotgetdataprint("全部评价")"""def getpositivecomment():css_sele1 = '#comment > div.mc > ments-list.ETab > div.tab-main.small > ul > li:nth-child(4)'css_sele2 = '#comments-list > div.mt > div > ul > li:nth-child(3)'css_sele3 = '#comments-list > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li:nth-child(3)'return get_datanum_bycssselectorlist([css_sele1, css_sele2, css_sele3], "好评(")"""try:mypositivecomment = get_element_bycssselector(css_sele1)data_num = mypositivecomment.get_attribute('data-num')mprint("1好评")if isString("好评(", mypositivecomment.text):print mypositivecomment.text + ":" + str(data_num) # mprint ("显⽰好评")mprint("好评数量⽆法获取")except:debugprint("第⼀次抓好评失败继续第⼆次")passtry:#书籍⾹蕉mypositivecomment = get_element_bycssselector(css_sele2)data_num = mypositivecomment.get_attribute('data-num')mprint("2好评")if isString("好评(", mypositivecomment.text):print mypositivecomment.text + ":" + str(data_num) # mprint ("显⽰好评")return data_numelse:mprint("好评数量⽆法获取")except:passtry:#??mypositivecomment = get_element_bycssselector(css_sele3)data_num = mypositivecomment.get_attribute('data-num')if isString("好评(", mypositivecomment.text):mprint ("第3次获取到好评")print mypositivecomment.text + ":" + str(data_num) # mprint ("显⽰好评")return data_numelse:mprint("好评数量⽆法获取")print mypositivecomment.text + ":" + str(data_num) # mprint ("显⽰好评")except:mprint("⽆法获取到好评")return warnningtext()"""def getmoderatecomment():css_sele1 = '#comment > div.mc > ments-list.ETab > div.tab-main.small > ul > li:nth-child(5)'css_sele2 = '#comments-list > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li:nth-child(4)'return get_datanum_bycssselectorlist([css_sele1, css_sele2], "中评(")"""try:css_sele = '#comment > div.mc > ments-list.ETab > div.tab-main.small > ul > li:nth-child(5)'mymoderatecomment = driver_wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_sele)))# mymoderatecomment = webdriver_chrome.find_element_by_css_selector(# "#comments-list > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li:nth-child(4)")data_num = mymoderatecomment.get_attribute('data-num')mprint("1中评")print mymoderatecomment.text + ":" + str(data_num) # mprint("显⽰中评")return data_numexcept:passtry:css_sele = '#comments-list > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li:nth-child(4)'mymoderatecomment = driver_wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_sele)))# mymoderatecomment = webdriver_chrome.find_element_by_css_selector(# "#comments-list > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li:nth-child(4)")data_num = mymoderatecomment.get_attribute('data-num')print mymoderatecomment.text + ":" + str(data_num) # mprint("显⽰中评")mprint("2中评")return data_numexcept:mprint("第⼆次中评失败联系开发")"""def getnegativecomment():css_sele1 = '#comment > div.mc > ments-list.ETab > div.tab-main.small > ul > li:nth-child(6)'css_sele2 = '#comments-list > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li:nth-child(5)'return get_datanum_bycssselectorlist([css_sele1, css_sele2], "差评(")"""try:css_sele = '#comment > div.mc > ments-list.ETab > div.tab-main.small > ul > li:nth-child(6)'mynegativecomment = driver_wait.until (EC.element_to_be_clickable((By.CSS_SELECTOR, css_sele)))data_num = mynegativecomment.get_attribute('data-num')mprint("1差评")print mynegativecomment.text+":"+str(data_num) # mprint ("显⽰差评")return data_numexcept:debugprint("第⼀次差评失败")try:css_sele = '#comments-list > div:nth-child(1) > div:nth-child(1) > ul:nth-child(1) > li:nth-child(5)'mynegativecomment = driver_wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_sele)))data_num = mynegativecomment.get_attribute('data-num')print mynegativecomment.text + ":" + str(data_num) # mprint ("显⽰差评")mprint("2差评")return data_numexcept:mprint("第2次差评失败联系开发")"""def getaddcomment():#追评css_sele1 = '#comment > div.mc > ments-list.ETab > div.tab-main.small > ul > li.J-addComment' return get_datanum_bycssselectorlist ([css_sele1, ], "追评(")"""try:css_sele = '#comment > div.mc > ments-list.ETab > div.tab-main.small > ul > li.J-addComment' maddcomment = driver_wait.until(EC.element_to_be_clickable ((By.CSS_SELECTOR, css_sele)))data_num = maddcomment.get_attribute('data-num')print maddcommentreturn data_numexcept:return"如果前⾯都没问题可能这个链接没有追评可以⼿动确认".decode("utf-8")"""def getcurrenturl():# debugprint("打印当前页⾯url: "+str(webdriver_chrome.current_url))return webdriver_chrome.current_urldef mwrite(linenum, zlist): #放⼀个要保存的⾏数和数据listcount = len(zlist) #列表数据的长度mprint("准备插⼊第 "+str(linenum+1)+" 条数据,⼀共:"+str(count)+"列")title_style = xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00')if linenum == 0:global wbglobal wswb = xlwt.Workbook()ws = wb.add_sheet("京东666".decode("utf-8"))for i in range(0, count):#列数if i == 0:mprint("写⼊如下数据")if linenum == 0:#第1条数据待插⼊需要先把标题插⼊0 再把第⼀条数据插⼊1ws.write(linenum, i, title[i].decode("utf-8"), title_style)#写标题ws.write(linenum+1, i, zlist[i])#这个write是⼀个覆盖操作如果没write就放空print title[i].decode("utf-8"), zlist[i]wb.save(xls_name)# if i == (count-1):# mprint("完成本条数据写⼊")else: # 第2+条数据开始插⼊ws = wb.get_sheet(0)ws.write(linenum+1, i, zlist[i])print title[i].decode ("utf-8"), zlist[i]wb.save(xls_name)# mprint("第"+str(linenum+1)+"条数据写⼊成功,还剩"+(sumurlcount-linenum)+"条数据待解析")class MyThread_totalcom(Thread):def __init__(self):Thread.__init__(self)def run(self):# totalcom = totalcomment()self.totalcom = totalcomment()def get_result(self):return self.totalcomclass MyThread_showpic(Thread):def __init__(self):Thread.__init__(self)def run(self):self.showpic = getshowpicnum()def get_result(self):return self.showpicdef getall(url):starttime = datetime.datetime.now()RETURN_CODE = openweb(url)print RETURN_CODE,'RETURN_CODE'if RETURN_CODE:#TRUE: skip and warningtry:if RETURN_CODE == 2:mprint("页⾯被跳转")skiplist = [url, "!!页⾯被跳转".decode("utf-8"), RETURN_CODE, "", "", "", "", ""]return skiplistelse:#1mprint("⽆法访问检查⽹络是否故障")skiplist = [url, "!!检查是否⽆法打开⽹页".decode("utf-8"), RETURN_CODE, "", "", "", "", ""]return skiplistexcept:mprint("")skiplist = [url, "!!跳过该条链接".decode("utf-8"), "".decode("utf-8"), "", "", "", "", ""]return skiplistelse:#FALSE :continue to get the data# starttime = datetime.datetime.now ()endtime = datetime.datetime.now()timed = (endtime - starttime).secondsmprint("⽹页已经被打开,耗时:"+str(timed)+"秒")debugprint('scrolldown1')#urlcurrent = getcurrenturl()#写⼀个如果链接被跳转到其他页⾯就跳过的判断有时间再写吧 urlcurrent可能变成 scrolldown()# msleep1()#scrolldown()# msleep2()debugprint('scrolldown2')name = getname()if isOffsale: # 下柜price = "商品已下柜".decode ("utf-8")else:price = getprice()clickcommentbtn()# msleep2()#好评度能加载完成就能显⽰晒图try:print u"好评度:", get_element_bycssselector("#comment > div.mc > ment-info.J-comment-info > ment-percent > div").text except:mprint("⽆法获取好评度,说明⽹络加载缓慢")#想写个多线程不过单独⼀个的时候正常如果两个都放进去就会出问题难道是selenium不能同时find两个element?mprint("多线程开始")thd1 = MyThread_totalcom()# thd2 = MyThread_showpic()thd1.start()mprint("MyThread_totalcom线程开始")# thd2.start()# mprint("MyThread_showpic程开始")thd1.join()# thd2.join()totalcom = thd1.get_result()# showpic = thd2.get_result()mprint("多线程结束")# totalcom = totalcomment()#上⾯⽤多线程这⾥就注释掉#上⾯多线程只能跑⼀个 totalcomment和getshowpicnum⼀起就出问题好像不是我多线程代码有问题是selenium不能同时find多个元素positivcom = getpositivecomment()modertcom = getmoderatecomment()negtivcom = getnegativecomment()# addcomment = getaddcomment()sumlist = [url, name, price, showpic, positivcom, modertcom, negtivcom, totalcom]# sumlist = [url, name, price, showpic, positivcom, modertcom, negtivcom ,addcomment]# print sumlistreturn sumlist # a listif __name__ == '__main__':try:#__main__# print type(now_time), type("时间")print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)# print ".",# time.sleep(0.2)cc = 0# URLSourcetotal_starttime = datetime.datetime.now()f = open(URLSource, "r")lines = f.readlines() # 读取全部内容global sumurlcountsumurlcount = len(lines)print sumurlcountmprint("⼀共 "+str(sumurlcount)+" 条数据要爬⾍")for jdurl in lines:#for i in urllist:s = []print jdurlone_starttime = datetime.datetime.now ()goodsinfo_list = getall(jdurl.replace("\n", ""))print "test111111111"# print goodsinfo_listmwrite(cc, goodsinfo_list)oneurl_endtime = datetime.datetime.now ()oneurl_timed = (oneurl_endtime - one_starttime).secondsmprint ("该条数据写⼊完成耗时:" + str (oneurl_timed) + "秒,还剩"+str(sumurlcount - cc - 1)+"条数据待分析,即将开始下⼀个链接的抓取 cc = cc + 1mprint("@@@@@$$$$$$$$@@@@@ 所有代码正常运⾏⽆报错 @@@@@@@@@@@$$$$$$$$$$$$$$$@@@@@@@@@@@@@@@@")total_endtime = datetime.datetime.now ()total_timed = (total_endtime - total_starttime).secondsmprint ("整个爬⾍⼀共耗时:" + str (total_timed) + "秒"+",单条链接平均爬⾍耗时:"+str((round(total_timed/sumurlcount,2)))+ "秒")except Exception, e:print Exception, emprint("~~~~~~~~中间有报错了@@@@@@@@@@@@@@@@")finally:mprint("sleep 10s后关闭浏览器")time.sleep(10)webdriver_chrome.quit()。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
通过selenium方式简单爬取京东搜索信息__伍德春
下列示例需要运行在python3.6.3,修改keyword和pages,对于网络速度不好的情况,需要适当调整time.sleep(值);需要chrome浏览器以及对应版本的chromedriver.exe;如果需要将数据写入到文件,可以print(item)处调用自定义的保存函数;此例子只是简单爬取了搜索出来的信息中的4项简单信息,如果还要爬取详细页面,还需要打开每个链接再爬取;python对大小写以及空格有严格的要求,需要注意。
from selenium import webdriver
import time
keyword='手机' #搜索关键字
pages=4 #爬取页数
#运行浏览器
driver=webdriver.Chrome('d:/selenium/chromedriver.exe')
driver.implicitly_wait(10)
driver.set_window_size(1920,1080)
#打开京东
driver.get('https://')
time.sleep(2)
for i in range(1,pages+1):
url='https:///Search?keyword='
url=url+keyword
url=url+'&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq='
url=url+keyword
url=url+'cid2=653&cid3=655&s=167&click=0'
url=url+'&page='+str(i)
driver.get(url)
print(url)
time.sleep(2)
js = "var q=document.documentElement.scrollTop=10000"
driver.execute_script(js)
time.sleep(3)
all_info=driver.find_elements_by_xpath('//*[@id="J_goodsList"]/ul/li') for x in all_info:
try:
价格=x.find_element_by_xpath('div/div[3]/strong/i').text
介绍= x.find_element_by_xpath('div/div[4]/a/em').text
评论= x.find_element_by_xpath('div/div[5]/strong/a').text
商店= x.find_element_by_xpath('div/div[7]/span/a').text
item=[价格,介绍,评论,商店]
print(item)
except:
print('出错')
time.sleep(12)。