1AttributeError: 'list' object has no attribute 'strip'原因

list 列表 不能用 .strip来去除空格

这是针对字符串的操作

2

除了strip 如何去除空格?replave方法

空格产生的原因:xpath爬出来自带换行符/n

即使replace掉了 也有在结果中产生实际换行

for id in [108702, 108701, 108700, 108699, 108697]:
    filmName = getdata.xpath('//*[@id="item'+str(id)+'"]/div/div[2]/div[4]/a/text()')
    print(filmName)
    for fname in filmName:
        replace = fname.replace('', '').replace(' ', '')
        if replace == '' or replace == '':
            continue
        else:
            print(fname)
filmName = getdata.xpath('//*[@id="item'+str(id)+'"]/div/div[2]/div[4]/a/text()')[1].replace('\n', '')
    print(filmName)

错误原因

xpath返回的是一个列表list,所以要提取列表的第二个元素(第一个元素是空格,根据实际情况判断)

#错误写法
url = 'https://www.douban.com/doulist/24213/'
data = requests.get(url, headers=headers).text
getdata = etree.HTML(data)

for id in [108702, 108701, 108700, 108699, 108697]:
    filmName = getdata.xpath('//*[@id="item'+str(id)+'"]/div/div[2]/div[4]/a/text()').strip()
    print(filmName)
 

4

正确

for id in [108702, 108701, 108700, 108699, 108697]:
    filmName = getdata.xpath('//*[@id="item'+str(id)+'"]/div/div[2]/div[4]/a/text()')[1].strip()
    print(filmName)
   

5

各种写法的返回情况

for id in [108702, 108701, 108700, 108699, 108697]:
    filmName = getdata.xpath('//*[@id="item'+str(id)+'"]/div/div[2]/div[4]/a/text()')[1].strip()
    print(filmName)

伴我同行 Stand by Me
跳出我天地 Billy Elliot
爱在黎明破晓前 Before Sunrise
爱在日落黄昏时 Before Sunset
艾德·伍德 Ed Wood

------------------------------------------------------------------------------


for id in [108702, 108701, 108700, 108699, 108697]:
    filmName = getdata.xpath('//*[@id="item'+str(id)+'"]/div/div[2]/div[4]/a/text()')
    print(filmName)
    for fname in filmName:
        replace = fname.replace('', '').replace(' ', '')
        if replace == '' or replace == '':
            continue
        else:
            print(fname)



['\n          ', '\n        伴我同行 Stand by Me\n      ']

          

        伴我同行 Stand by Me
      
['\n          ', '\n        跳出我天地 Billy Elliot\n      ']

          

        跳出我天地 Billy Elliot
      
['\n          ', '\n        爱在黎明破晓前 Before Sunrise\n      ']

          

        爱在黎明破晓前 Before Sunrise
      
['\n          ', '\n        爱在日落黄昏时 Before Sunset\n      ']

          

        爱在日落黄昏时 Before Sunset
      
['\n          ', '\n        艾德·伍德 Ed Wood\n      ']

          

        艾德·伍德 Ed Wood
      

Process finished with exit code 0

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐