gpt4 book ai didi

python - 从链接中提取 Scrapy

转载 作者:太空宇宙 更新时间:2023-11-04 10:23:42 25 4
gpt4 key购买 nike

我试图在某些链接中提取信息,但我无法转到链接,我从 start_url 中提取信息,但我不确定为什么。

这是我的代码:

import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from tutorial.items import DmozItem
from scrapy.selector import HtmlXPathSelector

class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python"
]
rules = [Rule(SgmlLinkExtractor(allow=[r'Books']), callback='parse')]


def parse(self, response):
hxs = HtmlXPathSelector(response)
item = DmozItem()

# Extract links
item['link'] = hxs.select("//li/a/text()").extract() # Xpath selector for tag(s)

print item['title']

for cont, i in enumerate(item['link']):
print "link: ", cont, i

我没有从“http://www.dmoz.org/Computers/Programming/Languages/Python/Books”获取链接,而是从“http://www.dmoz.org/Computers/Programming/Languages/Python”获取链接。

为什么?

最佳答案

要使 rules 起作用,您需要使用 CrawlSpider 而不是一般的 scrapy Spider。

此外,您需要将第一个解析函数重命名为 parse 以外的名称。否则,您将覆盖 CrawlSpider 的一个重要方法,它将无法工作。请参阅文档中的警告 http://doc.scrapy.org/en/0.24/topics/spiders.html?highlight=rules#crawlspider

您的代码正在抓取来自“http://www.dmoz.org/Computers/Programming/Languages/Python”的链接,因为 rule 命令被通用 Spider 忽略。

这段代码应该可以工作:

import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from dmoz.items import DmozItem
from scrapy.selector import HtmlXPathSelector

class DmozSpider(CrawlSpider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python"
]
rules = [Rule(SgmlLinkExtractor(allow=[r'Books']), callback='parse_item')]


def parse_item(self, response):
hxs = HtmlXPathSelector(response)
item = DmozItem()

# Extract links
item['link'] = hxs.select("//li/a/text()").extract() # Xpath selector for tag(s)

print item['link']

for cont, i in enumerate(item['link']):
print "link: ", cont, i

关于python - 从链接中提取 Scrapy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30753213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com