15-糗事百科(python+xpath)

來源:互聯網
上載者:User

標籤: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)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.