Python基於urllib,re爬取百度的國內即時新聞
阿新 • • 發佈:2018-01-05
正則匹配 分享 str 導入 findall term 下載 pytho tex Python應用於爬蟲領域業界已經相當的廣泛了,今天就采用urllib + re 爬取下百度國內即時新聞。
軟件環境:
Python : 3.6.0
PyCharm: Community 2017.2
Python 下載地址 https://www.python.org/downloads/
Pycharm 下載地址(Community是免費的) https://www.jetbrains.com/pycharm/download/#section=windows
主要思路:
采用urllib請求制定url,拿到網頁的html,然後采用re進行正則匹配找到新聞標題
爬取過程:
1. 導入urllib 和 re 兩個模塊
import urllib from urllib import request import re
2. 采用urllib.request.urlopen 打開百度信息url,並取得所有html
url = "http://news.baidu.com/guonei" response = urllib.request.urlopen(url) html = response.read().decode('utf-8')
urllib.urlopen()方法用於打開一個url地址。
read()方法用於讀取URL上的數據,並把整個頁面下載下來。
3. 在Chrome中按F12可以查看到網頁的源代碼,可以看到新聞位於 div id="instant-news"下面
4. 獲取即時信息的整個div的html並存儲到變量: instant_news_html
pattern_of_instant_news = re.compile('<div id="instant-news.*?</div>',re.S) instant_news_html = re.findall(pattern_of_instant_news, html)[0]
5. 從全部news的html中匹配出每一個新聞標題
pattern_of_news = re.compile('<li><a.*?>(.*?)</a></li>', re.S) news_list = re.findall(pattern_of_news, instant_news_html) for news in news_list: print(news)
將會看到如入結果
完整源代碼:
import urllib from urllib import request import re url = "http://news.baidu.com/guonei" response = urllib.request.urlopen(url) html = response.read().decode('utf-8') pattern_of_instant_news = re.compile('<div id="instant-news.*?</div>',re.S) instant_news_html = re.findall(pattern_of_instant_news, html)[0] pattern_of_news = re.compile('<li><a.*?>(.*?)</a></li>', re.S) news_list = re.findall(pattern_of_news, instant_news_html) for news in news_list: print(news)
參考資料:
urllib
re
Python基於urllib,re爬取百度的國內即時新聞