python爬虫学习过程中遇到的问题记录

一、xpath取出标签下的全部文本

在学习爬虫爬取百度搜索记录的过程中,想要提取搜索记录的标题,比如
python爬虫学习过程中遇到的问题记录
对应的HTML是:
python爬虫学习过程中遇到的问题记录
比如在上面的图片中,想打印出“使用apriori进行关联分析(一)-我是8位的-博客园”
我首先尝试了

content = selector.xpath('//*[@id="' + str(pn+i) + "\"]/h3/a[1]/text()")

发现打印出的结果是
python爬虫学习过程中遇到的问题记录
标签中的关键字“apriori”没有打印出来。
解决方法:

content = selector.xpath('//*[@id="' + str(pn+i) + "\"]/h3/a[1]")
for contents in content:
    print(contents[0].xpath('string(.)').strip())

修改后的结果
python爬虫学习过程中遇到的问题记录
参考博客:https://blog.****.net/zheng_lan_fang/article/details/78363280

二、list index out of range

爬虫遇到如下错误:
python爬虫学习过程中遇到的问题记录
是因为爬虫的过程中遇到了空值,解决方法是加上判断语句:

except IndexError:
    pass

参考博客:https://www.jianshu.com/p/f1b58ec12b72