如何用python爬虫代理ip爬取网页数据?

最新资讯发布日期:2021-03-06

image.png

在网络行销时代,许多模式已不能适应互联网新时代,常常无法达到行销效果,要想更好地运作网络行销,需要借助许多行销工具,做好每一步。与网络问答推广一样,代理IP的支持也是不可或缺的。必须在营销过程中寻找最有效的工具,提高效率,使网络营销效果最大化。

使用Python对网页表格数据进行爬行的代码如下。

'''
Python 3.x
描述:本DEMO演示了使用爬虫(动态)代理IP请求网页的过程,代码使用了多线程
逻辑:每隔5秒从API接口获取IP,对于每一个IP开启一个线程去抓取网页源码
'''
import requests
import time
import threading
from requests.packages import urllib3

ips = []

# 爬数据的线程类
class CrawlThread(threading.Thread):
   def __init__(self,proxyip):
       super(CrawlThread, self).__init__()
       self.proxyip=proxyip
   def run(self):
       # 开始计时
       start = time.time()
       #消除关闭证书验证的警告
       urllib3.disable_warnings()
       #使用代理IP请求网址,注意第三个参数verify=False意思是跳过SSL验证(可以防止报SSL错误)
       html=requests.get(url=targetUrl, proxies={"http" : 'http://' + self.proxyip, "https" : 'https://' + self.proxyip}, verify=False, timeout=15).content.decode()
       # 结束计时
       end = time.time()
       # 输出内容
       print(threading.current_thread().getName() +  "使用代理IP, 耗时 " + str(end - start) + "毫秒 " + self.proxyip + " 获取到如下HTML内容:\n" + html + "\n*************")

# 获取代理IP的线程类
class GetIpThread(threading.Thread):
   def __init__(self,fetchSecond):
       super(GetIpThread, self).__init__()
       self.fetchSecond=fetchSecond
   def run(self):
       global ips
       while True:
           # 获取IP列表
           res = requests.get(apiUrl).content.decode()
           # 按照\n分割获取到的IP
           ips = res.split('\n')
           # 利用每一个IP
           for proxyip in ips:
               if proxyip.strip():
                   # 开启一个线程
                   CrawlThread(proxyip).start()
           # 休眠
           time.sleep(self.fetchSecond)

if __name__ == '__main__':
   # 获取IP的API接口
   apiUrl = "http:xxxx"
   # 要抓取的目标网站地址
   targetUrl = "http://ip.chinaz.com/getip.aspx"
   # 获取IP时间间隔,建议为5秒
   fetchSecond = 5
   # 开始自动获取IP
   GetIpThread(fetchSecond).start()

本文介绍了用python爬虫代理ip爬取网页数据的方法。让我们浏览了解更多!
挂件 关闭
客服
二维码
客服二维码

加微信 领流量

大客户经理二维码

售前咨询,企业定制

专属客服竭诚为您服务