在使用python對(duì)網(wǎng)頁進(jìn)行多次快速爬取的時(shí)候,訪問次數(shù)過于頻繁,服務(wù)器不會(huì)考慮User-Agent的信息,會(huì)直接把你視為爬蟲,從而過濾掉,拒絕你的訪問,在這種時(shí)候就需要設(shè)置代理,我們可以給proxies屬性設(shè)置一個(gè)代理的IP地址,代碼如下:
import requests from lxml import etree url = "https://www.ip.cn" headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 OPR/57.0.3098.116", } pro = { # 'https': 'https://118.122.92.252:37901', #四川省成都市 電信 'https': 'https://27.17.45.90:43411', #湖北省武漢市 電信 } try: response = requests.get(url, headers=headers, proxies=pro) html_str = response.content.decode() # print(html_str) html = etree.HTML(html_str) message = html.xpath("http://div[@class='well']//p/text()") ip = html.xpath("http://div[@class='well']//p/code/text()") eng = html.xpath("http://div[@class='well']/p/text()") print(message[0]+ip[0]) print(message[1]+ip[1]) print(eng[2]) except requests.exceptions.ProxyError as e: print("當(dāng)前代理異常") except: print("當(dāng)前請(qǐng)求異常")
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。