Python獲取百度熱搜的完整代碼
好久沒寫了,就把上課做的一個小東西拿出來分享一下吧。百度網(wǎng)頁截圖如下 ↓↓↓
程序運行輸出結(jié)果截圖 ↓↓↓
上代碼 ↓↓↓
from lxml import etreefrom lxml import htmlimport requestsheaders={’User-Agent’:’Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36’}page = requests.get('https://www.baidu.com',headers=headers)html = page.text#print(source1)# 從字符串解析element = etree.HTML(html)# 元素列表,獲取的方式列出了如下兩種# ps = element.xpath(’//*[@id='hotsearch-content-wrapper']/li/a/span[2]’)ps = element.xpath(’//*[@class='title-content-title']’)#熱搜文本內(nèi)容text = []if len(ps) > 0: for p in ps: #輸出節(jié)點的文本 text1 = p.text text.append(text1)else: print('空') x = element.xpath(’//*[@class='s-hotsearch-content']/li’)#熱搜文本對應(yīng)的排名index = []for x1 in x: #獲取節(jié)點的屬性 index1 = x1.get('data-index') index.append(index1)print(text) print(index)#定義一個對文本和排名進(jìn)行匹配的函數(shù),返回一個字典型數(shù)據(jù)def PP(index_array,text_array): x = {} i = 0 for index_a in index_array: #index_a = int(index_a)x[index_a] = text_array[i] i = i + 1 return xre_text = PP(index,text)#對字典性數(shù)據(jù)按key進(jìn)行排序,即key=lambda re:re[0],排序完成后再轉(zhuǎn)換為字典型數(shù)據(jù)last_text = dict(sorted(re_text.items(),key=lambda re:re[0]))
到此這篇關(guān)于Python獲取百度熱搜的完整代碼的文章就介紹到這了,更多相關(guān)Python 百度熱搜內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP新手必備的基礎(chǔ)知識2. .NET 中配置從xml轉(zhuǎn)向json方法示例詳解3. 微信小程序?qū)崿F(xiàn)商品分類頁過程結(jié)束4. vue-electron中修改表格內(nèi)容并修改樣式5. 推薦一個好看Table表格的css樣式代碼詳解6. ASP常用日期格式化函數(shù) FormatDate()7. 利用FastReport傳遞圖片參數(shù)在報表上展示簽名信息的實現(xiàn)方法8. phpstudy apache開啟ssi使用詳解9. HTML中的XML數(shù)據(jù)島記錄編輯與添加10. 以PHP代碼為實例詳解RabbitMQ消息隊列中間件的6種模式
