Python3 类、传递变量的麻烦



>练习/尝试学习美丽的汤和使用对象/类。

我创建了一个基本的网络抓取工具,可以抓取一个网站上的页面,但我正在尝试将所有内容分开,以便抓取工具能够识别出它与 url 中的哪个网站并自动抓取。

问题是我不知道如何在我的对象之间很好地传递网站名称。我尝试使用变量"网站",但我不确定如何实际使用它。

在此之前有一些位,但这是我坚持的部分。

class AllProductsPage:
def __init__(self, page_content):
self.soup = BeautifulSoup(page_content, 'html.parser')
@property
def products(self, website):
store_product_locator = ProductLocator.(website)
return [ProductParser(e) for e in self.soup.select(store_product_locator)]
class ProductLocator:
website_to_scrape = "div.product-item.js-product-data"

我希望能够有多个"website_to_scrape",根据"网站"变量是什么,自动使用定位器,例如"网站 = website_to_scrape_7">

我应该让网站变量成为所有类的全局变量吗?这是正常的事情吗?

最后想通了,只是将网站作为参数传递到 ProductLocator 中,并将定位器放入字典中,我循环并与网站输入进行比较。

我现在可以添加更多定位器,它在解析时会自动为每个网站使用正确的定位器。

最新更新