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'