在利用Selenium爬取页面信息的时候突然报错,第一条信息爬取的时候还好好的,第二条就不行了。

请参考网上的爬取代码:

 # coding=utf-8
"""
Created on 2015-12-10 @author: Eastmount
利用Selenium爬取百度百科5A级景区的内容介绍的代码
""" import time
import re
import os
import sys
import codecs
import shutil
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.action_chains import ActionChains # Open PhantomJS
# driver = webdriver.PhantomJS(executable_path="D:\phantomjs-2.1.1-windows\sbin\phantomjs.exe")
driver = webdriver.PhantomJS(executable_path="D:\phantomjs-1.9.8-windows\phantomjs.exe")
# driver = webdriver.Firefox()
wait = ui.WebDriverWait(driver, 10) # 显示等待时间(实例,最大等待时间) # Get the Content of 5A tourist spots
def getInfobox(entityName, fileName):
try:
# create paths and txt files
print(u'文件名称: ', fileName)
info = codecs.open(fileName, 'w', 'utf-8') # locate input notice: 1.visit url by unicode 2.write files
# Error: Message: Element not found in the cache
# Perhaps the page has changed since it was looked up
# 解决方法: 使用Selenium和Phantomjs print(u'实体名称: ', entityName.rstrip('\n'))
driver.get("http://baike.baidu.com/")
elem_inp = driver.find_element_by_xpath("//form[@id='searchForm']/input")
# elem_inp = driver.find_elements_by_xpath("//div[@class='lemma-summary']/div")
elem_inp.send_keys(entityName)
elem_inp.send_keys(Keys.RETURN)
info.write(entityName.rstrip('\n') + '\r\n') # codecs不支持'\n'换行 # load content 摘要
elem_value = driver.find_elements_by_xpath("//div[@class='lemma-summary']/div")
for value in elem_value:
print(value.text)
info.writelines(value.text + '\r\n') # 爬取文本信息
# 爬取所有段落<div class='para'>的内容 class='para-title'为标题 [省略] time.sleep(2)
# except Exception as e: # 'utf8' codec can't decode byte
# print("Error: ", e)
finally:
print('\n')
info.close() # Main function
def main():
# By function get information
path = "BaiduSpider\\"
if os.path.isdir(path):
shutil.rmtree(path, True)
os.makedirs(path)
source = open("Tourist_spots_5A.txt", 'r')
num = 1
for entityName in source:
# entityName = unicode(entityName, "utf-8")
if u'故宫' in entityName: # else add a '?'
entityName = '北京故宫'
# else: Name = entityName.rstrip('\n')
name = "%04d" % num
fileName = path + str(name) + ".txt"
getInfobox(entityName, fileName)
num = num + 1
print('End Read Files!')
source.close()
driver.close() if __name__ == '__main__':
main()

执行报错信息为:

Traceback (most recent call last):
File "D:/pycharm/untitled_DB/wordcloud/selenium爬取百度百科/Selenium_baidu.py", line 85, in <module>
main()
File "D:/pycharm/untitled_DB/wordcloud/selenium爬取百度百科/Selenium_baidu.py", line 77, in main
getInfobox(entityName, fileName)
File "D:/pycharm/untitled_DB/wordcloud/selenium爬取百度百科/Selenium_baidu.py", line 41, in getInfobox
elem_inp.send_keys(Keys.RETURN)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 479, in send_keys 'value': keys_to_typing(value)})
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 628, in _execute
return self._parent.execute(command, params)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute
self.error_handler.check_response(response)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 208, in check_response
raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message: TypeError - 'undefined' is not a function (evaluating '_getTagName(currWindow).toLowerCase()')

找了1天都没找到原因,真的 死烦 ,找到原因是71行代码写死,然而要是不加判断也会出现这样的报错,比较郁闷,后来查了半天资料,在Stackoverflow的评论中找到思路,很有可能是read文件的时候,读取到的内容格式有问题,于是查看了一下格式发现,果不其然,多了一个"/n",修改代码:

if u'故宫' in entityName:  # else add a '?'
  entityName = '北京故宫'
else:
  entityName = entityName.rstrip('\n')
name = "%04d" % num
fileName = path + str(name) + ".txt"
getInfobox(entityName, fileName)
num = num + 1

在执行,ok,请忽略渣渣排版

关于这个该死的报错:TypeError - 'undefined' is not a function (evaluating '_getTagName(currWindow).toLowerCase()')的更多相关文章

  1. jquery TypeError: 'undefined' is not a function (evaluating 'elem.nodeName.toLowerCase()') [jquery.js:1904]错误原因

    今天,某个环境报了个js错误,TypeError: 'undefined' is not a function (evaluating 'elem.nodeName.toLowerCase()') [ ...

  2. react-native 编译报错: undefined is not an object (evaluating '_react2.PropTypes.func')

    情况通报: 因为是我的二维码模块报错,提示报错代码如下 重要信息是下面的红色字体部分(Android 模拟器红屏) undefined is not an object (evaluating '_r ...

  3. 【已解决】React项目中按需引入ant-design报错TypeError: injectBabelPlugin is not a function

    react项目中ant-design按需加载,使用react-app-rewired的时候报错 运行npm start或者yarn start报如下错误: TypeError: injectBabel ...

  4. 报错TypeError: $(...).live is not a function解决方法

    报错的原因是这个方法在jquery1.7以后就被废除了, 1.7以后的版本改用.on()方法 之前的用法: .live(events, function) 新方法: .on(eventType, se ...

  5. flvjs的unload(),detachMediaElement(),destroy()报错,undefined,not a function解决方案

    首先,真的被网上一堆各种转载复制粘贴坑了不少,最后直接到GitHub上flvjs的看作者的demo和docs才解决,具体如下. 1.引入flvjs文件,新建实例 var flvUrl = '直播流地址 ...

  6. layui的layer独立版报错“TypeError: i is not a function”的解决

    折腾良久发现是引入jQuery顺序的问题. jQuery必须在layer引入之前引入.

  7. [转载]UEditor报错TypeError: me.body is undefined

    本文转载来自:UEditor报错TypeError: me.body is undefined 今天在使用UEditor的setContent的时候报错,报错代码如下 TypeError: me.bo ...

  8. VUE.JS 使用axios数据请求时数据绑定时 报错 TypeError: Cannot set property 'xxxx' of undefined 的解决办法

    正常情况下在data里面都有做了定义 在函数里面进行赋值 这时候你运行时会发现,数据可以请求到,但是会报错 TypeError: Cannot set property 'listgroup' of ...

  9. Node中使用MySQL报错:TypeError: Cannot read property 'query' of undefined

    Node中使用MySQL报错: TypeError: Cannot read property 'query' of undefined at /Users/sipeng/Desktop/彭思/201 ...

随机推荐

  1. BZOJ 3512: DZY Loves Math IV [杜教筛]

    3512: DZY Loves Math IV 题意:求\(\sum_{i=1}^n \sum_{j=1}^m \varphi(ij)\),\(n \le 10^5, m \le 10^9\) n较小 ...

  2. Redis安装和基础介绍

    一:初识Redis Redis是一个远程内存数据库,它不仅性能强劲,而且还具有复制特性以及为解决问题而生的独一无二的数据模型.Redis提供了5种不同类型的数据结构,各式各样的问题都可以很自然地映射到 ...

  3. Burp_用户名密码爆破

    burp 全称 Burp Suite, 是用于攻击web 应用程序的集成平台.它包含了许多工具,可以抓包可以爆破也可以扫描漏洞. 主要组件如下: Proxy--是一个拦截HTTP/S的代理服务器,作为 ...

  4. [Python Study Notes]电池信息

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ...

  5. WPF项目学习.三

    工具代码记录 版权声明:本文为博主初学经验,未经博主允许不得转载. 一.前言 记录在学习与制作WPF过程中遇到的解决方案. 分页控件的制作,邮件发送,日志代码,excel导入导出等代码的实现过程: 二 ...

  6. mac下自带的Apache+PHP环境输出错误提示

    sudo vim /etc/php.ini 找到 display_errors = Off ,把Off 改为 On . 最后为 display_errors = On ; 找到 error_repor ...

  7. linux下卸载已安装的软件

    1.先查询该软件是否安装,是否存在 rpm -qa | grep -i teamview 2.根据一中的结果(软件包名称),执行如下命令 rpm -e [软件包名]

  8. 一个例子理解break和continue的区别

    结论:break用于终止整个循环,而continue用于终止某一次循环.public class Test { public static void main(String[] args) { for ...

  9. [翻译] 编写高性能 .NET 代码--第二章 GC -- 减少分配率, 最重要的规则,缩短对象的生命周期,减少对象层次的深度,减少对象之间的引用,避免钉住对象(Pinning)

    减少分配率 这个几乎不用解释,减少了内存的使用量,自然就减少GC回收时的压力,同时降低了内存碎片与CPU的使用量.你可以用一些方法来达到这一目的,但它可能会与其它设计相冲突. 你需要在设计对象时仔细检 ...

  10. Netbeans简要配置许可证信息

    <#if licenseFirst??>${licenseFirst}</#if>${licensePrefix}Copyright (C) <2017>  < ...