在利用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. 用icas下载文件报错

    前段时间服务器升级,过程中测试到报表下载,报表下载要用到icas,用的是sdts-client.jar,但是此jar包有两种连接模式,分别为: public static final SdtsConn ...

  2. JS 特殊字符的验证的问题

    个人的JS 的收集方便下次的使用做百度查询: 1. 特殊字符的验证: var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].&l ...

  3. 文件读写io操作范例

    系统io读写,copy int main(int argc, char **argv) {  if(argc != 3) {   printf("Usage: %s <src> ...

  4. php+redis 学习 三 乐观锁

    <?php header('content-type:text/html;chaeset=utf-8'); /** * redis实战 * * 实现乐观锁机制 * * @example php ...

  5. TensorFlow实战之实现自编码器过程

    关于本文说明,已同步本人另外一个博客地址位于http://blog.csdn.net/qq_37608890,详见http://blog.csdn.net/qq_37608890/article/de ...

  6. linux scp远程拷贝文件及文件夹

    [http://www.jb51.net/LINUXjishu/73131.html] 1.拷贝本机/home/administrator/test整个目录至远程主机192.168.1.100的/ro ...

  7. go get报错unrecognized import path “golang.org/x/net/context”…

    今天安装gin框架,首先下载gin,命令如下:go get github.com/mattn/go-sqlite3 结果报错: package golang.org/x/net/context: un ...

  8. ASP.NET MVC5+EF6+EasyUI 后台管理系统(89)-EF执行SQL语句与存储过程

    这一节,我们来看看EF如何执行SQL语句与读取存储过程的数据,可能有一部分人,还不知道EF如何执行存储过程与原生SQL语句! 我们什么时候要直接使用原生的SQL语句? 返回值过于复杂 过于复杂的联合查 ...

  9. 机器学习03:K近邻算法

    本文来自同步博客. P.S. 不知道怎么显示数学公式以及排版文章.所以如果觉得文章下面格式乱的话请自行跳转到上述链接.后续我将不再对数学公式进行截图,毕竟行内公式截图的话排版会很乱.看原博客地址会有更 ...

  10. OpenCMS模板的导出和OpenCMS网站的导出

    1.OpenCMS模板的导出 (1)切换到Administration视图,单击Module Management,如图所示:   (2)导出位置:tomcat根目录\webapps\opencms\ ...