python獲取百度熱榜連結的例項方法
阿新 • • 發佈:2020-08-28
目標網址:
https://www.baidu.com/
要獲取的內容:
連結分析:
從下圖可以看出只需要獲取關鍵字,再構建就可以了。
完整程式碼:
importrequests importpprint importre importurllib.parse url='https://www.baidu.com/' headers={ 'Host':'www.baidu.com','Referer':'https://www.baidu.com/','User-Agent':你的User-Agent,'Cookie':你的Cookie } response=requests.get(url,headers=headers).content.decode('utf-8') #獲取關鍵字 pat='"pure_title":"(.*?)"' keyword=re.findall(pat,response,re.S) print(len(keyword)) forhot_wordinkeyword: #漢字不符合url標準,所以這裡需要進行url編碼 i=urllib.parse.quote(hot_word,encoding='utf-8',errors='replace') #url構建 link=f'https://www.baidu.com/s?cl=3&tn=baidutop10&fr=top1000&wd={i}&rsv_idx=2&rsv_dl=fyb_n_homepage&hisfilter=1' print(link)
你會發現結果很長:
但其實關鍵字後面的幾個引數是可以去掉的,這樣url就沒有那麼長了。
內容擴充套件:
python 爬取簡單的百度搜索結果
爬取百度搜索結果
主要還要藉助xpath helper谷歌瀏覽器的外掛來操作更容易找到需要查詢資訊的xpath位置
還要首先了解一下百度搜索請求的引數 lm預設為0,天數限制,但是好像只有1有用。
預設每頁10條資訊,rn
pn是頁碼
from lxml import etree import re import requests import string import json headers = { "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/68.0.3440.106 Safari/537.36" } response = requests.get('https://www.baidu.com/s?wd=騰訊視訊優惠&lm=1',headers=headers) r = response.text html = etree.HTML(r,etree.HTMLParser()) r1 = html.xpath('//h3') r2 = html.xpath('//*[@class="c-abstract"]') r3 = html.xpath('//a[@class="c-showurl"]') for i in range(10) : r11 = r1[i].xpath('string(.)') r22 = r2[i].xpath('string(.)') r33 = r3[i].xpath('string(.)') # with open('test.txt','a',encoding='utf-8') as f: # f.write(json.dumps(r11,ensure_ascii=False) + '\n') # f.write(json.dumps(r22,ensure_ascii=False) + '\n') # f.write(json.dumps(r33,ensure_ascii=False) + '\n') print(r11,end='\n') print(r22,end='\n') print(r33) print()
到此這篇關於python獲取百度熱榜連結的例項方法的文章就介紹到這了,更多相關教你用python獲取百度熱榜連結內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!