我已经用 python 编写了一些代码,我的目的是将“web_parser”类新生成的链接提供给“get_docs”类。但是,我想不出有什么有效的方法可以做到这一点。我想做的就是在两个类之间建立连接,以便“web_parser”类生成链接,“get_docs”类处理它们以获得精炼的输出。任何有关我如何完美地做到这一点的想法都将受到高度赞赏。提前致谢。
from lxml import html
import requests
class web_parser:
page_link = "https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=San%20Francisco%2C%20CA"
main_url = "https://www.yellowpages.com"
def __init__(self, link):
self.link = link
self.vault = []
def parser(self):
self.get_link(self.page_link)
def get_link(self, url):
page = requests.get(url)
tree = html.fromstring(page.text)
item_links = tree.xpath('//h2[@class="n"]/a[@class="business-name"][not(@itemprop="name")]/@href')
for item_link in item_links:
self.vault.append(self.main_url + item_link)
class get_docs(web_parser):
def __init__(self, new_links):
web_parser.__init__(self, link)
self.new_links = [new_links]
def procuring_links(self):
for link in self.vault:
self.using_links(link)
def using_links(self, newly_created_link):
page = requests.get(newly_created_link)
tree = html.fromstring(page.text)
name = tree.findtext('.//div[@class="sales-info"]/h1')
phone = tree.findtext('.//p[@class="phone"]')
print(name, phone)
if __name__ == '__main__':
crawl = web_parser(web_parser.page_link)
parse = get_docs(crawl)
parse.parser()
parse.procuring_links()
我对创建类知之甚少,所以请原谅我的无知。在此阶段执行时,我收到错误:
web_parser.__init__(self, link)
NameError: name 'link' is not defined
最佳答案
我不太确定你想如何使用它,通过向 web_parser 提供参数或在类中使用硬编码链接?
根据您在 __main__
中使用的命令,您可以进行如下处理:
class get_docs(object):
def __init__(self, web_parser):
self.vault = web_parser.vault
if __name__ == '__main__':
crawl = web_parser() # create an instance
crawl.parser()
parse = get_docs(crawl) # give the instance to get_doc, or directly the vault with crawl.vault
parse.procuring_links() # execute get_doc processing
__
您还需要更正 web_parser 类:
您必须在创建期间给定的参数 (link
) 或硬编码的 page_link 之间进行选择,只需调整方法 parser()
来定位好的参数即可。
class web_parser:
def __init__(self, link=''):
self.link = link
self.vault = []
self.page_link = "https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=San%20Francisco%2C%20CA"
self.main_url = "https://www.yellowpages.com"
关于python - 无法在两个类之间建立桥梁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45259900/