python - 项目不包含在 Scrapy 中的 for 循环中

标签 python mysql xpath scrapy

我认为这个问题可能有一个简单的解决方案...我想做的就是使用我的变量项 ['genre'] 提取列出流派类型的文本,足够简单...但是,作为我提取的项目仅出现在我正在抓取的页面上,当循环遍历其他项目(例如项目['artist'])时,不包括项目['流派']。任何帮助,将不胜感激。这是我认为相关的代码。

def parse_item(self, response):#http://stackoverflow.com/questions/15836062/scrapy-crawlspider-doesnt-crawl-the-first-landing-page
    for info in response.xpath('//div[@class="entry vevent"] | //div[@id="page"]'):
        item = TutorialItem() # Extract items from the items folder.
        item ['artist'] = info.xpath('.//span[@class="summary"]//text()').extract() # Extract artist information.
        item ['date'] = info.xpath('.//span[@class="dates"]//text()').extract() # Extract date information.
        preview = ''.join(str(s)for s in item['artist'])
        item ['genre'] = info.xpath('.//div[@class="header"]//text()').extract()

真的希望这是有道理的,如果没有,抱歉!

最佳答案

您只获得流派一次的原因是,response.xpath('//div[@class="entry vevent"] |//div的返回列表[@id="page"]') 将包含一个 div(带有 id="page") 和一堆 div(带有 class="entry vevent")

在迭代上面的列表时,div[@id="page"]将满足流派 xpath,

即,此 div 包含另一个 div,该 div 具有 class="header"

In [1]: a = response.xpath('//div[@class="entry vevent"] | //div[@id="page"]')

In [2]: a[0].xpath('.//div[@class="header"]//text()').extract()
Out[2]: [u'Clubbing Overview']

In [3]: a[1].xpath('.//div[@class="header"]//text()').extract()
Out[3]: []

In [4]: a[2].xpath('.//div[@class="header"]//text()').extract()
Out[4]: []
...

另一边div[@class="entry vevent"],它不包含任何具有class="header的div 所以最终会导致得到空列表作为输出

有道理吗?

一个解决方案是将流派 xpath 放在循环之外,或者您可以将流派的 xpath 修改为

info.xpath('.//div[@class="header"]//text() | ./parent::div[@class="rows"]/preceding-sibling::div[@class="header"]//text()').extract()

关于python - 项目不包含在 Scrapy 中的 for 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29570682/

相关文章:

c# - 使用 C# 抓取网页 (html)

python - 无法在 suds 中创建 SOAP 过滤器

python - 在 python urllib.urlretrieve 中设置推荐 url

mysql:我可以在慢查询日志中看到空间不足中止查询吗

MySQL Create Table Like with Engine 覆盖

mysql - MySQL中模式/数据库之间的区别

python - 抽象类应该返回与预期实现方法相同的类型吗?

Python3 Tkinter 文本小部件在同一行插入

java - XML、XPATH 添加值

xml - 用 bash 解析 HTML 表格列