首先要有一些準備工作,當然前提是需要了解一下python的基礎知識。
安裝所需要的語言環境和工具:
1、python 我使用的是python3.6.5版本
2、三方庫 requests
安裝命令:pip3 install requests
3、 Beautiful Soup
安裝命令:pip3 install bs4
4、lxml
安裝命令:pip3 install lxml
5、Pycharm
一個python的IDE 官網地址:https://www.jetbrains.com/pycharm/
當然也可以在終端直接編碼
上碼:
用pycharm創建一個python工程,然後創建一個python文件,比如 test.py,然後貼入下面代碼,之後運行。
import requests
from bs4 import BeautifulSoup
mheaders = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh;q=0.6",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"Host": "s.weibo.com",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"
}
targetUrl = 'https://s.weibo.com/top/summary?cate=realtimehot'
response = requests.get(targetUrl, headers=mheaders).text
soup = BeautifulSoup(response, 'lxml')
sort = 0
for hot_td in soup.find_all('td', class_="td-02"):
# 標題
hotTitle = hot_td.find('a').string
sort += 1
print('第%s位 %s ' % (sort, hotTitle))
輸入結果:
簡單說明:
1、requests是一個python的三方網絡庫,提供了簡潔的http get\post請求等方法。requests.get(targetUrl, headers=mheaders) 這裏的get就代表的是get方式請求,設置了headers是爲了把請求僞裝成瀏覽器請求,避免請求被攔截掉。
2、BeautifulSoup可以代替使用正則表達式去找到我們要抓取的html標籤。soup.find_all(‘td’, class_=“td-02”) 就代表找到所有的class="td-02"的td標籤。 在目標網站查看網頁源代碼可以看到要抓取的內容的樣子爲:
<td class="td-02">
<a href="/weibo?q=%23%E6%B8%85%E6%98%8E%E8%BF%BD%E6%80%9D%E5%AE%B6%E5%9B%BD%E6%B0%B8%E5%BF%B5%23&Refer=new_time" target="_blank">清明追思家國永念
</a>
</td>
...等等....
同理,hot_td.find(‘a’).string 就是在td標籤中找到 a 標籤取它包含的內容,就是我們要抓取的熱搜內容了。
最後:
抓取的庫還有很多種,真正的項目中還要考慮很多,比如如何抓取下一頁內容、更換ip、數據入庫等等,這裏就當是自學了python之後,體驗抓取的一個小demo。
今天是2020年4月4日,清明節,全國人民在今天爲抗擊疫情犧牲的英雄們默哀!不用多言,都在心裏!祖國加油!