无法理解用Python编写的粘贴代码中使用的点符号

时间:2017-03-26 18:18:52

标签: python web-crawler

最近,通过Python爬虫的代码,我在某些时候陷入困境,无法理解用于通过PPN和CURRENT_APP从app类调用LINKS的点符号[两者都被标记并用等号表示然后是(This One)标记,表示我指的是哪条线。我的问题是PPN和CURRENT_APP如何用点符号调用LINKS?

from lxml import html
import requests

class app_crawler:
    def __init__(self,starturl,depth):
        self.starturl=starturl
        self.depth=depth
        self.current_depth=0
        self.depth_links=[]
        self.apps=[]
    def crawler(self):
        ppn=self.get_app(self.starturl)
        self.apps.append(ppn)
        self.depth_links.append(ppn.links)=======================================[This One]
        while self.current_depth < self.depth:
            current_links=[]
            for link in self.depth_links[self.current_depth]:
                current_app=self.get_app(link)
                current_links.extend(current_app.links)===================[This One]
                self.apps.append(current_app)
                self.current_depth+=1
                self.depth_links.append(current_links)


    def get_app(self,link):
        page = requests.get(link)
        tree = html.fromstring(page.text)
        name = tree.xpath('//h1[@itemprop="name"]/text()')[0]
        developper=tree.xpath('//div[@class="left"]/h2/text()')[0]
        price=tree.xpath('//div[@itemprop="price"]/text()')[0]
        links=tree.xpath('//div[@class="lockup-info"]//*/a[@class="name"]/@href')
        app=App(name, developper, price, links)
        return app


class App:
    def __init__(self,name,developper,price,links):
        self.name=name
        self.developper=developper
        self.price=price
        self.links=links========================================================[This One]

    def __str__(self):
        return ("Name: "+self.name +"\nDevelopper: "+self.developper+"\nPrice: "+self.price+"\n")

crawl=app_crawler("https://itunes.apple.com/us/app/candy-crush-saga/id553834731?mt=8",1)
crawl.crawler()
for data in crawl.apps:
    print(data)

1 个答案:

答案 0 :(得分:0)

由于Links是ppn,current_app的成员,因此可以从它们访问它。 这里ppn和current_app是从get_app方法创建的,看到链接是在方法内部创建的,并传递给App constructer。

链接= tree.xpath( '// DIV [@类= “锁止信息”] // * / A [@类= “名称”] / @ HREF') app = App(名称,开发者,价格,链接)