导入模块
from bs4 import BeautifulSoup
import urllib3
import urllib
import threading
Urllib3+BeautifulSoup+Thread:多线程爬虫教程(爬取西刺代理IP)
爬虫是学python中最好玩的学习方法,也是方便生活、工作中的有效利器,爬虫帮我们工作,那会节省大量的人力。
在该博客中,分成5个步骤来简单教大家如何用好爬虫。最后贴出源码。
1 函数:获取网页内容
urllib3一般是爬虫中必用的打开网页的利器,西刺网站不需要验证用户,获取网页十分简单。若想进一步了解详见官网(英文):http://urllib3.readthedocs.io/en/latest/ ,中文优秀博客:https://blog.csdn.net/LookForDream_/article/details/78624594
#获取网页HTML码
def getContent(url):
http=urllib3.PoolManager()
response=http.request('get',url)
#网页返回200表示可打开网页
print('网页 %s 返回代码:%s'%(url,response.status))
return response.data
2 获取每页的代理IP
该步骤是爬虫中最核心的部分,要分析出爬取的网页的规律。网页规律分析不好,写出来的代码可能又臭又长。BeautifulSoup是较为容易上手的解析网页的爬虫工具,BeautifulSoup可调用xml、html.parser、lxml解析器,性能优点各有不同,而官网推荐我们使用lxml解析器。BeautifulSoup中文官网:https://blog.csdn.net/kikaylee/article/details/56841789
Proxys=[]
pages=5
#爬去西刺10页的代理IP
for i in range(0,pages):
url='http://www.xicidaili.com/nn/%d'%(i+1)
content=getContent(url) #获取网页内容