在利用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. CentOS7修改SSH远程连接端口

      CentOS7修改SSH远程连接端口              

  2. NOIP 2017 day 1 游记

    心情非常复杂.大概就是我问到的所有人都A掉了T1那样. 的确没有按套路出牌,今年T1不是大模拟,反倒是T2. ……已经不想再提到今天的T1了.如果真的要我说,我只能说 我再次学了一整年的OI,结果栽到 ...

  3. Kafka基本知识回顾及复制

    Producers发布记录到集群,集群维护这些记录并且将记录分发给Consumers. 在Kafka中,最关键的抽象是topic.Producers发布记录到一个topic,Consumers订阅一个 ...

  4. AWS-SS配置过程

    为满足家长要求,以下只录步骤: 远端: 1. 注册并启动一个AWS实例.这一步网上N多教程,搜 AWS EC2 等均可. 2. 远程安装SS,并写配置文件.依然网搜, AWS S(hadow)S(oc ...

  5. CentOS7中关闭firewall,并使用iptables管理防火墙

    背景描述 在使用Docker时,启用centos7默认的firewall,启动端口映射时,防火墙规则不生效.docker默认使用了iptables防火墙机制.所以需要关闭firewall使用iptab ...

  6. Hive入门教程

    Hive 安装 相比起很多教程先介绍概念,我喜欢先动手装上,然后用例子来介绍概念.我们先来安装一下Hive 先确认是否已经安装了对应的yum源,如果没有照这个教程里面写的安装cdh的yum源http: ...

  7. 编译安装python3.6后pip3无法安装模块问题处理

    编译安装python3.6之后,使用pip3命令安装第三方库效果如图所示: pip is configured with locations that require TLS/SSL, however ...

  8. ZK客户端脚本的简单使用

    sh zkCli.sh [-server ip:port] :连接节点zk客户端[-server ip:port 用于连接集群中指定节点的客户端] 1.创建节点 create [-s] [-e] pa ...

  9. 面试陷阱1:Integer类型的比较

    public class Test01 { public static void main(String[] args) { Integer f1 = 100, f2 = 100, f3 = 150, ...

  10. [UWP]做个调皮的BusyIndicator

    1. 前言 最近突然想要个BusyIndicator.做过WPF开发的程序员对BusyIndicator应该不陌生,Extended WPF Toolkit 提供了BusyIndicator的开源实现 ...