您的位置:首页 > 编程语言 > Python开发

python爬虫爬取goubanjia的代理ip

2017-12-21 21:34 393 查看
今天这里介绍一下python3爬取http://www.goubanjia.com的代理ip的方法,这个网站的html有点变态,还做了js加密。对于初学python的我还是有一定的难道,但是研究了一段时间,写下了一个demo。接下来跟他家分享一下。

from bs4 import BeautifulSoup
from urllib import parse,request
class Spider:
def __init__(self):
self.beginPage = int(input("请输入起始页:"))
self.endPage = int(input("请输入终止页:"))

self.url = 'http://www.goubanjia.com/free/'
self.ua_header = {"User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1 Trident/5.0;"}

def tiebaSpider(self):
for page in range(self.beginPage, self.endPage + 1):
#拼接访问的地址
myUrl = self.url +"index%d.shtml"%page
self.loadPage(myUrl)

# 读取页面内容
def loadPage(self, url):
req = request.Request(url, headers = self.ua_header)
resHtml = request.urlopen(req).read()

# 解析html
html=BeautifulSoup(resHtml,"lxml")
#获取所以的ip的td
tdResultList=html.select('td[class="ip"]')
for tdResult in tdResultList:
#获取当前td所以的子标签
childList= tdResult.find_all()
text=""
for child in childList:
if 'style' in child.attrs.keys():
if child.attrs['style'].replace(' ','')=="display:inline-block;":
if child.string!=None:
text=text+child.string
#过滤出端口号
elif 'class'in child.attrs.keys():
classList=child.attrs['class']
if 'port' in classList:
port=self.get_poxy(classList[1])
#拼接端口
text=text+":"+str(port)

else:
if child.string != None:
text = text + child.string

#写入到文件
self.writeToTxt(text)

#解码端口号
def get_poxy(self,port_word):
word = list(port_word)
num_list = []
for item in word:
num = 'ABCDEFGHIZ'.find(item)
num_list.append(str(num))

port = int("".join(num_list)) >> 0x3
return port

def writeToTxt(self, text):
txtFile = open("portFile.txt", 'a+')
txtFile.write(text+"\n")
txtFile.close()

# 模拟 main 函数
if __name__ == "__main__":

# 首先创建爬虫对象
mySpider = Spider()
# 调用爬虫对象的方法,开始工作
mySpider.tiebaSpider()


因为初学python代码写的还不够好,希望大家多提意见,共同学习,也希望对你有所帮助。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 爬虫