爬取下来的title已列表形式存储,如何保存到文件中?

 

#需求:获取58同城二手房的房源信息
#url:https://huzhou.58.com/ershoufang
import requests
from lxml import etree

if __name__ == "__main__":
    url='https://huzhou.58.com/ershoufang'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.81'
    }
    #获取页面源码
    html = requests.get(url=url,headers=headers).text
    #进行数据解析
    tree = etree.HTML(html)  #实例化一个etree对象
    title = tree.xpath('//div[@class="property-content"]//h3/text()')
    #print(li_list)
    fp =open('58.text','w',encoding='utf-8')
    fp.write(title+'\n')

报错信息:TypeError: can only concatenate list (not "str") to list

视频中老师是通过for 循环将所有的标题爬下来,但是我这样写好像也是可以把所有的标题爬下来。

视频中的58二手房网页HTML源码和我现在去访问时的写法不一样。所以不知道我这样写的有没有问题。

tree.xpath 解析出来的是列表,你需要将其转换成字符串形式写入txt文档。可将最后两行改为:

with open('58.txt','w',encoding='utf-8') as fp:

  fp.write('\n'.join(title))

其实,我没明白,你要问什么,

1、如果内容已经是列表了,那么可以直接转为字符串保存到文件中

2、你报错到原因是title是list类型,不是str类型,如果要保存,可以转为str保存即可