python爬虫爬取goubanjia的代理ip

来源:互联网 发布:数据库发展方向 编辑:程序博客网 时间:2024/05/16 20:51

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

from bs4 import BeautifulSoupfrom urllib import parse,requestclass 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代码写的还不够好,希望大家多提意见,共同学习,也希望对你有所帮助。

原创粉丝点击