0

例如,在这个 python 代码中。

from scrapy.loader import ItemLoader
from myproject.items import Product

def parse(self, response):
    l = ItemLoader(item=Product(), response=response)
    l.add_xpath('name', '//div[@class="product_name"]')
    l.add_xpath('name', '//div[@class="product_title"]')
    l.add_xpath('price', '//p[@id="price"]')
    l.add_css('stock', 'p#stock]')
    l.add_value('last_updated', 'today') # you can also use literal values
    return l.load_item()

如何避免使用“名称”、“价格”作为字符串。有什么方法可以使用,比如

 l.add_xpath(getname(Product.name), '//div[@class="product_title"]')
 l.add_xpath((getname(Product.price), '//p[@id="price"]')

谢谢

4

1 回答 1

0

通过使用getattr内置函数

 product = Product()
 l.add_xpath(getattr(product, 'name'), '//div[@class="product_title"]')
于 2020-04-06T11:31:30.147 回答