0
点赞
收藏
分享

微信扫一扫

链接爬虫与多线程爬虫是什么

爬虫的几大框架就是那么几个,运用熟悉对于自己爬虫工作效率也是得心应手,今天我们就利用案例来学习下爬虫的一些经常遇到问题。

链接爬虫

爬虫时经常碰到网页中有连接跳转的情况,我们想要的数据又需要跳转连接才能取到,这就需要使用到链接爬虫,而链接爬虫的主要步骤如下:

链接爬虫与多线程爬虫是什么_多线程

首先要确定要爬取的内容的入口链接,然后根据情况编写正则表达式来提取入口链接。

UA模拟浏览器,以及反反爬来爬取页面。

使用编写好的正则表达式开始提取入口链接,并过滤掉重复的链接,最后将链接打印到屏幕上。

反反爬主要用到UA、reference、设置header信息等反反爬技术来模拟用户操作浏览器;提取链接主要用到的方法是re.compile、findall(data)等,对于重复的链接可以使用list(set(link))来实现多余元素的过滤,在过滤完成后返回过滤后的列表。

多线程爬虫

之前设计的爬虫都是从上往下依次执行的,也就是单线程爬虫,而在爬虫中使用多线程爬虫技术就可以实现部分爬虫分别执行,也就是在多条线上执行,这种执行结构是多线程爬虫,极大的提高了爬虫的效率,这里拿python来举例,在python中使用多线程需要使用threading模块,为了使用多线程,可以编写一个类继承thread类,把这个类作为一个线程,并使用__init__(selt)方法来初始化这个线程,然后再在run(self)方法编写这个线程要执行的代码逻辑,这个线程类不一定是一个,可以编写多个这样的线程类并通过start()方法来启动这些线程。

代码示例

import threading
import time
class myThread(threading.Thread):
def __init__(self, name, delay):
threading.Thread.__init__(self)
self.name = name
self.delay = delay
def run(self):
print("Starting " + self.name)
print_time(self.name, self.delay)
print("Exiting " + self.name)
def print_time(threadNmae, delay):
counter = 0
while counter < 3:
time.sleep(delay)
print(threadNmae, time.ctime())
counter += 1
threads = []
thread1 = myThread(name="Thread-1", delay=1)
thread2 = myThread(name="Thread-2", delay=2)

免费爬虫ip的使用

我们可以从网上获取免费的爬虫ip:

import requests,random

#定义爬虫ip池
proxy_list = [
'182.39.6.245:38634',
'115.210.181.31:34301',
'123.161.152.38:23201',
'222.85.5.187:26675',
'123.161.152.31:23127',
]

# 提取ip链接:http://jshk.com.cn/mb/reg.asp?kefu=xjy
# 随机选择一个爬虫ip
proxy = random.choice(proxy_list)

proxies = {
'http': 'http://' + proxy,
'https': 'https://' + proxy,
}
try:
response = requests.get('http://www.baidu.com', proxies=proxies)
print(response.text)
except requests.exceptions.ConnectionError as e:
print('Error', e.args)

requests中使用收费爬虫ip

import requests

# 从爬虫ip服务中获取一个爬虫ip
proxy = requests.get("http://jshk.com.cn/mb/reg.asp?kefu=xjy").text
proxies = {
'http': 'http://' + proxy,
'https': 'https://' + proxy,
}
try:
response = requests.get('http://www.baidu.com', proxies=proxies)
print(response.text)
except requests.exceptions.ConnectionError as e:
print('Error', e.args)


举报

相关推荐

0 条评论