报IndexError: list index out of range错误

来源:9-6 selenium的安装和使用

慕沐9123820

2020-07-12

代码:

topic_url = parse.urljoin(domain, tr.xpath(".//td[3]/a/@href").extract()[-1])
topic_title = tr.xpath(".//td[3]/a/text()").extract()[-1]

报错:

/Users/shihaotian/Desktop/venv/lib/python3.7/site-packages/pymysql/cursors.py:170: Warning: (1364, "Field 'author_id' doesn't have a default value")
  result = self._query(query)
Traceback (most recent call last):
  File "/Users/shihaotian/PycharmProjects/untitled/spider.py", line 126, in <module>
    parse_list(url)
  File "/Users/shihaotian/PycharmProjects/untitled/spider.py", line 81, in parse_list
    topic_url = parse.urljoin(domain, tr.xpath(".//td[3]/a/@href").extract()[-1])
IndexError: list index out of range

上面取[-1]是因为csdn在第一二条中新增了推荐a标签,所以取最后一个能正常取得数据

写回答

1回答

bobby

2020-07-13

这个地方是tr.xpath(".//td[3]/a/text()")这个没有获取到数据,你用try except处理一下就行了

0
6
bobby
回复
慕沐9123820
加你了
2020-07-22
共6条回复

Python爬虫工程师实战 大数据时代必备

慕课网严选精品教程,高质量内容+服务!

2377 学习 · 1158 问题

查看课程