获取标签全部文本的方式

1.获取最外层标签,遍历内部所有的子标签,获取标签文本

选择贴吧小说吧中的一个为例 链接为     https://tieba.baidu.com/p/5815118868?pn=1

#找到指定类名的div标签 该标签内为贴吧内容和作者的集合体
div_list = response.xpath('//div[@class="l_post l_post_bright j_l_post clearfix  "]')

#遍历内部所有子标签
for div in div_list:
    author = div.xpath('.//div[@class="louzhubiaoshi_wrap"]').extract()
    print(author)

2.正则去掉标签,re.compile.sub()

remove = re.compile('\s')
douhao = re.compile(',')
content = ''
for string in content_list:
    string = re.sub(remove,'',string)
    string = re.sub(douhao,'',string)
    print(string)

3./text()获取标签的文本  //text() 获取标签以及子标签的文本

content_list = div.xpath('.//div[@class="d_post_content j_d_post_content "]//text()').extract()

4.使用xpath('string(.)') ,这种方式来获取所有文本

content = div.xpath('.//div[@class="d_post_content j_d_post_content "]').xpath('string(.)').extract()[0]+'\n'

猜你喜欢

转载自blog.csdn.net/weixin_42660771/article/details/81460143