【问题标题】:How to get all outbound links in a given webpage and follow them? [closed]如何获取给定网页中的所有出站链接并关注它们? [关闭]
【发布时间】:2014-11-28 18:15:03
【问题描述】:

我有这段代码可以获取网页中的所有链接:

from scrapy.spider import Spider
from scrapy import Selector
from socialmedia.items import SocialMediaItem
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor

class MySpider(Spider):
    name = 'smm'
    allowed_domains = ['*']
    start_urls = ['http://en.wikipedia.org/wiki/Social_media']
    def parse(self, response):
        items = []
        for link in response.xpath("//a"):
            item = SocialMediaItem()
            item['SourceTitle'] = link.xpath('/html/head/title').extract()
            item['TargetTitle'] = link.xpath('text()').extract()
            item['link'] = link.xpath('@href').extract()
            items.append(item)
        return items

我想做以下事情: 1)不是获取所有链接,而是只获取出站链接,或者至少只获取那些以 http/s 开头的链接 2) 按照出站链接 3)只有在元数据中包含一些关键字时才抓取下一个网页 4)对给定数量的循环重复整个过程 任何人都可以帮忙吗? 干杯!

丹妮

【问题讨论】:

  • 感谢您提出一个单独的问题,而不是尝试在 cmets 中解决一个单独的问题来解决不同问题的答案。
  • 不客气?你能帮忙吗?

标签: python web-scraping scrapy scrape


【解决方案1】:

我想你可能正在寻找像 scrapy 的 Rule 和 LinkExtractor 这样的东西。

from scrapy.contrib.spiders import Rule
from scrapy.contrib.linkextractors import LinkExtractor
class MySpider(Spider):
    name = 'smm'
    allowed_domains = ['*']
    start_urls = ['http://en.wikipedia.org/wiki/Social_media']
    rules = (
        Rule(LinkExtractor(restrict_paths=('//a[contains(., "http")]'), callback='pre_parse')
    )

def pre_parse(self, response):
    if keyword in response.body:
        parse(response)

def parse(self, response):

这段代码完全未经测试,但只是提供了一个关于如何获取所有链接的想法,然后在进行完整解析之前检查后续页面的关键字。

祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    相关资源
    最近更新 更多