我使用scrapy从网站中提取各种一般数据,如标题、h1、h2、img和alts。我已经让它在标题,h1和h2s上运行得很好。但我在提取src和alts时遇到了一些问题。
我知道可以使用这样的语法提取srcs和alts (在本例中是src):
hxs = HtmlXPathSelector(response)
for img in hxs.select('//img/@src').extract():我的问题是,我想循环每一个图像,然后保存src和alts到不同的模型。
这些是我的模型:
class Page(models.Model):
website = models.ForeignKey(Website)
url = models.CharField(max_length=200, unique=True)
class Image(models.Model):
page = models.ForeignKey(Page)
src = models.CharField(max_length=300, unique=True)
class Alt(models.Model):
image = models.ForeignKey(Image)
text = models.CharField(max_length=200) 这是我到目前为止掌握的密码。
hxs = HtmlXPathSelector(response)
for img in hxs.select('//img').extract():
hxs2 = HtmlXPathSelector(img)
try:
i = Image(page=page, src=hxs2.select('//img/@src'))
i.save()
except:
pass
try:
a = Alt(image=i, text=hxs2.select('//img/@alt'))
a.save()
except:
pass这不太管用。我得到了以下错误:
exceptions.TypeError: cannot create weak reference to 'unicode' object我的问题是,这是一个好的方法,还是我应该尝试其他的?可能是regex,因为我每次都会有一组非常定义的html?
发布于 2013-10-08 13:24:40
.select()已经返回了一个HtmlXPathSelector的列表(参见嵌套选择器),所以我认为您需要这样的内容:
hxs = HtmlXPathSelector(response)
for img in hxs.select('//img'):
try:
i = Image(page=page, src=img.select('@src').extract()[0])
i.save()
except:
pass
try:
a = Alt(image=i, text=img.select('@alt').extract()[0])
a.save()
except:
passhttps://stackoverflow.com/questions/19248194
复制相似问题