Python Scrapy在本地主机上工作正常吗?
我写了一个爬虫程序,用来抓取一些HTML标签。现在的问题是,这个爬虫在互联网上的某个网址上运行得很好,但在本地(localhost)的网址上却不行。我的意思是,即使本地的网址是完全正确的,爬虫在访问本地资源时也会出错,而同样的资源在网上的网址上却能正常工作。有人能帮我解答这个疑惑吗?
def parse(self, response):
hxs = HtmlXPathSelector(response)
con = MySQLdb.connect(host="localhost",
user = "username",
passwd="psswd",
db ="dbname")
cur = con.cursor()
title = hxs.select("//h3")[0].extract()
desc = hxs.select("//h2").extract()
a = hxs.select("//meta").extract()
cur.execute("""Insert into heads(h2) Values(%s )""",(a))
con.commit()
con.close()
1 个回答
1
这个错误
exceptions.IndexError: list index out of range
出现在这一行
title = hxs.select("//h3")[0].extract()
说明列表 hxs.select("//h3")
是空的([]
),因为你试图用 hxs.select("//h3")[0]
来访问第一个元素(索引0),但Python告诉我们这个索引超出了范围。
你正在解析的HTML里显然没有 <h3>
标签。
另外,在你修复上面的错误后,还需要在 (a)
中的 a
后面加一个逗号,变成 (a,)
:
cur.execute("""Insert into heads(h2) Values(%s )""",(a,))
(a)
被解释为 a
,而 (a,)
则表示一个包含1个元素的元组。