Python爬取大量数据时,如何防止IP被封
前兩天我爬取了豬八戒上的一些數據網址::http://task.zbj.com/t-ppsj/p1s5.html,可能是由于爬取的數據量有點多吧,結果我的IP被封了,需要自己手動來驗證解封ip,但這顯然阻止了我爬取更多的數據了。
下面是我寫的爬取豬八戒的被封IP的代碼
我發現代碼運行完后,后面有幾頁數據沒有被爬取,我再也沒有辦法去訪問豬八戒網站了,等過了如何才能去訪問他們的網站,這就很尷尬了,我得防止被封IP
如何防止爬取數據的時候被網站封IP這里有一些套路。查了一些套路
1.修改請求頭
之前的爬蟲代碼沒有添加頭部,這里我添加了頭部,模擬成瀏覽器去訪問網站
2.采用代理IP
當自己的ip被網站封了之后,只能采用代理ip的方式進行爬取,所以每次爬取的時候嘗試用代理ip來爬取,封了代理還有代理。
這里我引用了這個博客的一段代碼來生成ip地址:http://blog.csdn.net/lammonpeter/article/details/52917264
生成代理ip,大家可以直接把這個代碼拿去用
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' # coding=utf-8 # IP地址取自國內髙匿代理IP網站:http://www.xicidaili.com/nn/ # 僅僅爬取首頁IP地址就足夠一般使用from bs4 import BeautifulSoup import requests import randomdef get_ip_list(url, headers):web_data = requests.get(url, headers=headers)soup = BeautifulSoup(web_data.text, 'lxml')ips = soup.find_all('tr')ip_list = []for i in range(1, len(ips)):ip_info = ips[i]tds = ip_info.find_all('td')ip_list.append(tds[1].text + ':' + tds[2].text)return ip_listdef get_random_ip(ip_list):proxy_list = []for ip in ip_list:proxy_list.append('http://' + ip)proxy_ip = random.choice(proxy_list)proxies = {'http': proxy_ip}return proxiesif __name__ == '__main__':url = 'http://www.xicidaili.com/nn/'headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'}ip_list = get_ip_list(url, headers=headers)proxies = get_random_ip(ip_list)print(proxies)好了我用上面的代碼給我生成了多個ip地址(有些ip地址可能無效,但只要不封我自己的ip就可以了,哈哈),然后我就可以在我的請求標題添加ip地址
**給我們的請求添加代理ip **
proxies = {'http': 'http://124.72.109.183:8118','http': 'http://49.85.1.79:31666'} user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4295.400'headers = {'User-Agent': user_agent} htmlText = requests.get(url, headers=headers, timeout=3, proxies=proxies).text目前知道的就
最后完整代碼如下:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006 尋找有志同道合的小伙伴, 互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' # coding=utf-8import requests import time from lxml import etreedef getUrl():for i in range(33):url = 'http://task.zbj.com/t-ppsj/p{}s5.html'.format(i+1)spiderPage(url)def spiderPage(url):if url is None:return Nonetry:proxies = {'http': 'http://221.202.248.52:80',}user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4295.400'headers = {'User-Agent': user_agent}htmlText = requests.get(url, headers=headers,proxies=proxies).textselector = etree.HTML(htmlText)tds = selector.xpath('//*[@class="tab-switch tab-progress"]/table/tr')for td in tds:price = td.xpath('./td/p/em/text()')href = td.xpath('./td/p/a/@href')title = td.xpath('./td/p/a/text()')subTitle = td.xpath('./td/p/text()')deadline = td.xpath('./td/span/text()')price = price[0] if len(price)>0 else '' # python的三目運算 :為真時的結果 if 判定條件 else 為假時的結果title = title[0] if len(title)>0 else ''href = href[0] if len(href)>0 else ''subTitle = subTitle[0] if len(subTitle)>0 else ''deadline = deadline[0] if len(deadline)>0 else ''print price,title,href,subTitle,deadlineprint '---------------------------------------------------------------------------------------'spiderDetail(href)except Exception,e:print '出錯',e.messagedef spiderDetail(url):if url is None:return Nonetry:htmlText = requests.get(url).textselector = etree.HTML(htmlText)aboutHref = selector.xpath('//*[@id="utopia_widget_10"]/div[1]/div/div/div/p[1]/a/@href')price = selector.xpath('//*[@id="utopia_widget_10"]/div[1]/div/div/div/p[1]/text()')title = selector.xpath('//*[@id="utopia_widget_10"]/div[1]/div/div/h2/text()')contentDetail = selector.xpath('//*[@id="utopia_widget_10"]/div[2]/div/div[1]/div[1]/text()')publishDate = selector.xpath('//*[@id="utopia_widget_10"]/div[2]/div/div[1]/p/text()')aboutHref = aboutHref[0] if len(aboutHref) > 0 else '' # python的三目運算 :為真時的結果 if 判定條件 else 為假時的結果price = price[0] if len(price) > 0 else ''title = title[0] if len(title) > 0 else ''contentDetail = contentDetail[0] if len(contentDetail) > 0 else ''publishDate = publishDate[0] if len(publishDate) > 0 else ''print aboutHref,price,title,contentDetail,publishDateexcept:print '出錯'if '_main_':getUrl()
數據全部爬取收回來了,且我的IP也沒有被封。當然防止被封IP肯定不止這些了,這還需要進一步探索!
最后
雖然數據我是已經抓取過來了,但是我的數據都沒有完美呈現,只是呈現在我的控制臺上,這并不完美,我應該寫入execl文件或者數據庫中啊,這樣才能方便采用。所以接下來我準備了使用Python操作execl
總結
以上是生活随笔為你收集整理的Python爬取大量数据时,如何防止IP被封的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 10 个小技巧:快速用 Python 进
- 下一篇: 上千个电脑文件怎么搬?用Python一键