| Google 新聞-焦點新聞 範例 |
以 InfoLite (Chrome擴充工具) 可以發現我們要擷取的資料在網頁原始碼中的 .esc-body 和 .esc-lead-article-title 兩個 class 中可以找到。
工具:
工具:
Python Packages 也可以 pip 方式進行安裝:
export http_proxy=http://proxy.hinet.net:80 export https_proxy=http://proxy.hinet.net:80 pip install requests pip install BeautifulSoup4
程式:
# coding=utf-8
import requests
from bs4 import BeautifulSoup
res = requests.get("https://news.google.com")
soup = BeautifulSoup(res.text)
print soup.select(".esc-body")
count = 1
for item in soup.select(".esc-body"):
print '======[',count,']========='
news_title = item.select(".esc-lead-article-title")[0].text
news_url = item.select(".esc-lead-article-title")[0].find('a')['href']
print news_title
print news_url
count += 1
Python3 版本 (2017/04/02新增)
#!/usr/bin/env python3
# coding=utf-8
# -*- coding: utf8 -*-
from urllib.request import urlopen
from bs4 import BeautifulSoup
res = urlopen("https://news.google.com")
soup = BeautifulSoup(res, "html.parser")
#print soup.select(".esc-body")
count = 1
for item in soup.select(".esc-body"):
print('======[',count,']=========')
news_title = item.select(".esc-lead-article-title")[0].text
news_url = item.select(".esc-lead-article-title")[0].find('a')['href']
print(news_title)
print(news_url)
count += 1
執行結果:
======[ 1 ]========= 美河市案宣判柯P解讀:2個小官非常賤 http://www.chinatimes.com/realtimenews/20151228002594-260401 ======[ 2 ]========= 北海道巴士對撞11台灣客受傷【更新】 http://www.cna.com.tw/news/firstnews/201512285015-1.aspx ======[ 3 ]========= 邱毅再爆816專案小英研究兩國論索262萬 http://www.chinatimes.com/realtimenews/20151228002822-260401 ======[ 4 ]========= 芝加哥警射殺2非裔家屬淚訴停止暴力 http://www.cna.com.tw/news/firstnews/201512285013-1.aspx ... ======[ 40 ]========= 食安再爆!素食也不安全蒟蒻竟摻工業用碱粉 http://www.uho.com.tw/hotnews.asp?aid=39330 ======[ 41 ]========= (用錯染髮劑增膀胱癌風險,3大守則安心變色/圖片取自優活健康網) http://www.uho.com.tw/hotnews.asp?aid=39317 ======[ 42 ]========= 當市長完成創傷急救體系柯P感概想到朱立倫 http://news.ltn.com.tw/news/politics/breakingnews/1553878
延伸閱讀:
參考資料:
- YouTube : 開始使用Python撰寫網路爬蟲 (Crawler)
- Beautiful Soup Documentation (官網文件說明)
#
沒有留言:
張貼留言