[英]Scrapy/Python/XPath - How to extract data from within data?
我是Scrapy的新手,我剛剛開始研究XPath。
我正在嘗試從div中的html列表項中提取標題和鏈接。 下面的代碼是我以為我會去做的,(選擇ul div,通過id,然后循環遍歷列表項):
def parse(self, response):
for t in response.xpath('//*[@id="categories"]/ul'):
for x in t.xpath('//li'):
item = TgmItem()
item['title'] = x.xpath('a/text()').extract()
item['link'] = x.xpath('a/@href').extract()
yield item
但是我收到了與此嘗試相同的結果:
def parse(self, response):
for x in response.xpath('//li'):
item = TgmItem()
item['title'] = x.xpath('a/text()').extract()
item['link'] = x.xpath('a/@href').extract()
yield item
導出的csv文件包含源代碼從上到下的li數據...
我不是專家,我已經做了很多嘗試,如果有人能夠對此有所了解,我將不勝感激。
您需要使用點開始在內部循環內使用的xpath表達式:
for t in response.xpath('//*[@id="categories"]/ul'):
for x in t.xpath('.//li'):
這將使其在當前元素的范圍內進行搜索,而不是整個頁面。
在使用相對XPath時查看更多解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.