Con*_*sta 1 python web-crawler scrapy python-2.7 scrapy-spider
我现在开始使用Scrapy了,我从一个体育页面(足球运动员的名字和团队)中获取了我想要的内容,但是我需要按照链接搜索更多的团队,每个团队页面都有一个链接对于玩家页面,网站链接的结构是:
团队页面:http://esporte.uol.com.br/futebol/clubes/vitoria/ players页面:http://esporte.uol.com.br/futebol/clubes/vitoria/jogadores/
我已经阅读了一些Scrapy教程,我在想团队页面,我必须关注链接,不要解析任何东西,玩家页面我不得跟随并解析玩家,我不知道我是不是我对这个想法是对的,而且语法错了,如果我的跟随想法是错误的,欢迎任何帮助.
这是我的代码:
class MoneyballSpider(BaseSpider):
name = "moneyball"
allowed_domains = ["esporte.uol.com.br", "click.uol.com.br", "uol.com.br"]
start_urls = ["http://esporte.uol.com.br/futebol/clubes/vitoria/jogadores/"]
rules = (
Rule(SgmlLinkExtractor(allow=(r'.*futebol/clubes/.*/', ), deny=(r'.*futebol/clubes/.*/jogadores/', )), follow = True),
Rule(SgmlLinkExtractor(allow=(r'.*futebol/clubes/.*/jogadores/', )), callback='parse', follow = True),
)
def parse(self, response):
hxs = HtmlXPathSelector(response)
jogadores = hxs.select('//div[@id="jogadores"]/div/ul/li')
items = []
for jogador in jogadores:
item = JogadorItem()
item['nome'] = jogador.select('h5/a/text()').extract()
item['time'] = hxs.select('//div[@class="header clube"]/h1/a/text()').extract()
items.append(item)
print item['nome'], item['time']
return items
Run Code Online (Sandbox Code Playgroud)
首先,由于你需要遵循提取链接,你需要一个CrawlSpider而不是一个BaseSpider.然后,您需要定义两个规则:一个用于具有回调的玩家,一个用于没有的团队,以遵循.此外,您应该从包含团队列表的URL开始,例如http://esporte.uol.com.br/futebol.这是一个完整的蜘蛛,可以让不同球队的球员回归:
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import Rule, CrawlSpider
from scrapy.item import Item, Field
from scrapy.selector import HtmlXPathSelector
class JogadorItem(Item):
nome = Field()
time = Field()
class MoneyballSpider(CrawlSpider):
name = "moneyball"
allowed_domains = ["esporte.uol.com.br", "click.uol.com.br", "uol.com.br"]
start_urls = ["http://esporte.uol.com.br/futebol"]
rules = (Rule(SgmlLinkExtractor(allow=(r'.*futebol/clubes/.*?/jogadores/', )), callback='parse_players', follow=True),
Rule(SgmlLinkExtractor(allow=(r'.*futebol/clubes/.*', )), follow=True),)
def parse_players(self, response):
hxs = HtmlXPathSelector(response)
jogadores = hxs.select('//div[@id="jogadores"]/div/ul/li')
items = []
for jogador in jogadores:
item = JogadorItem()
item['nome'] = jogador.select('h5/a/text()').extract()
item['time'] = hxs.select('//div[@class="header clube"]/h1/a/text()').extract()
items.append(item)
print item['nome'], item['time']
return items
Run Code Online (Sandbox Code Playgroud)
从输出引用:
...
[u'Silva'] [u'Vila Nova-GO']
[u'Luizinho'] [u'Vila Nova-GO']
...
[u'Michel'] [u'Guarani']
[u'Wellyson'] [u'Guarani']
...
Run Code Online (Sandbox Code Playgroud)
这只是暗示您继续处理蜘蛛,您需要进一步调整蜘蛛:根据您的需要选择合适的起始URL等.
希望有所帮助.
| 归档时间: |
|
| 查看次数: |
164 次 |
| 最近记录: |