標籤:with creat 表達 原碼 agent comment open lis created
爬取糗事百科的段子:
1.用xpath分析首要爬去內容的運算式;
2.用發起請求,獲得原碼;
3.用xpath分析源碼,提取有用資訊;
4.由python格式轉為json格式,寫入檔案
#_*_ coding: utf-8 _*_‘‘‘Created on 2018年7月17日@author: sssfunction: 爬取糗事百科裡面的內容‘‘‘import requestsimport jsonfrom lxml import etreeurl = "https://www.qiushibaike.com/8hr/page/3/"headers = {‘User-Agent‘: ‘Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1 Trident/5.0;‘}html= requests.get(url, headers = headers).text# print(html)#將返回的字串格式,轉為HTML DOM模式text = etree.HTML(html)#獲得包含每個糗事的鏈表#返回所有糗事的節點位置,contains()模糊查詢方法,第一個參數為要匹配的標籤,第二個參數為標籤的內容node_list = text.xpath(‘//div[contains(@id, "qiushi_tag_")]‘)items = {}for node in node_list: #使用者名稱# username = node.xpath(‘./div/a/h2‘)[0].text username = node.xpath(‘.//h2‘)[0].text #圖片串連 image = node.xpath(‘.//img/@src‘)#[0] #取出標題下的內容 content = node.xpath(‘./a/div/span‘)[0].text #點贊 zan = node.xpath(‘./div/span/i‘)[0].text #評論 comment = node.xpath(‘./div/span/a/i‘)[0].text items = { ‘username‘ : username, ‘image‘ : image, ‘content‘ : content, ‘zan‘ : zan, ‘comments‘ : comment } #把python格式的轉換為json格式,此時轉換成了字串,就可以寫入糗事段子.txt檔案中了 we=json.dumps(items, ensure_ascii=False) print(we) with open(‘qiushi.txt‘, ‘a‘, encoding=‘utf-8‘) as f: #注意在這裡轉為utf-8格式 f.write((we + ‘\n‘))
效果:
15-糗事百科(python+xpath)