iT邦幫忙

2

python爬蟲

  • 分享至 

  • xImage

小弟是自學程式的新手,在爬蟲上遇到一些問題,想請各位前輩們指點,
這是我嘗試想要爬臺灣期貨交易所行情資訊網的程式碼。
執行後會被免責說明阻擋,無法抓取到網址下的內容,還請各位前輩們能給小弟指點一下。
import requests
from bs4 import BeautifulSoup

url = 'https://mis.taifex.com.tw/futures/RegularSession/EquityIndices/FuturesDomestic/'
webpage = requests.post(url)
soup = BeautifulSoup(webpage.text,'lxml')
print(soup.text)

ccutmis iT邦高手 2 級 ‧ 2021-02-24 12:18:10 檢舉
我寫了一個 Python + Selenium 的範例給你參考 希望有幫助!
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

11
ccutmis
iT邦高手 2 級 ‧ 2021-02-24 12:50:44
最佳解答

Python跟Selenium的環境建置可以參考這篇文章的解答:
https://ithelp.ithome.com.tw/questions/10201921

Pythn+Selenium環境建置好之後可以用一個簡單的 Python Selenium 達到你要的結果,範例如下:

testSelenium.py

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

options = Options()
options.add_argument("--disable-notifications")

# 輸入chrome driver 路徑
chromedriver = r'C:\chromedriver\chromedriver.exe'
# 啟動 chrome driver
dirver = webdriver.Chrome(chromedriver, chrome_options=options)
# 指定開啟網址
url="https://mis.taifex.com.tw/futures/RegularSession/EquityIndices/FuturesDomestic/"
dirver.get(url)
time.sleep(5) #假設頁面在5秒內會載入完成
dirver.find_element_by_xpath("//button[text()='接受']").click()
while True:
    time.sleep(5)
    #每隔5秒印出當前網頁源碼
    print(dirver.page_source)

程式執行時會開一個chrome網頁,進到行情資訊網會暫停5秒,然後按"接受"按鈕,之後就是每隔五秒會把當前網頁源碼Print到螢幕上,有網頁源碼後續怎麼處理就看個人習慣了...。

用 Python+Selenium 比較易用的原因之一就是它更容易通過反爬虫機制,畢竟執行時它就的是開一個chrome自動化執行,header跟一些session,cookie會自己生成,如果你用的是requests或requests_html之類的,你要騙過反爬機制就要寫偽裝header跟session,cookie生成等等的處理,另外還有爬虫要有節制(time.sleep)就算是用python+selenium,短時間大量對伺服器進行一些request一樣是會被當爬虫封掉,設5秒鐘或更長一點的時間算是合理而且有道德的爬虫人士。

我要發表回答

立即登入回答