python獲取百度熱榜鏈接的實例方法
目標網址:
https://www.baidu.com/
要獲取的內容:
鏈接分析:
從下圖可以看出只需要獲取關鍵字,再構建就可以了。
完整代碼:
import requestsimport pprintimport reimport urllib.parseurl = ’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))for hot_word in keyword: # 漢字不符合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 etreeimport reimport requestsimport stringimport jsonheaders = { '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.texthtml = 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獲取百度熱榜鏈接內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: