【问题标题】:crawlspider not crawling using urls in text filescrawlspider 不使用文本文件中的 url 进行爬行
【发布时间】:2015-03-11 07:03:11
【问题描述】:

问题陈述:

我在每行的文件名 myurls.csv 中有一个论坛网址列表,如下所示:

https://www.drupal.org/user/3178461/track
https://www.drupal.org/user/511008/track

我写了一个CrawlSpider代码来爬取论坛帖子如下:

class fileuserurl(CrawlSpider):
    name = "fileuserurl"
    allowed_domains = []
    start_urls = []

    rules = (
    Rule(SgmlLinkExtractor(allow=('/user/\d/track'),
    restrict_xpaths = ('//li[@class="pager-next"]',),
    canonicalize=False ),callback='parse_page',follow=True)
    )

    def __init__(self):
    f = open('./myurls.txt','r').readlines()
    self.allowed_domains = ['www.drupal.org']
    self.start_urls = [l.strip() for l in f]
    super(fileuserurl,self).__init__()

    def parse_page(self, response):
    print '*********** START PARSE_PAGE METHOD**************'
    # print response.url
    items = response.xpath("//tbody/tr")
    myposts=[]
    for temp in items:
    item = TopicPosts()
    item['topic'] = temp.xpath(".//td[2]/a/text()").extract()
    relative_url = temp.xpath(".//td[2]/a/@href").extract()[0]
    item['topiclink'] = 'https://www.drupal.org'+relative_url
    item['author'] = temp.xpath(".//td[3]/a/text()").extract()
    try:
    item['replies'] = str(temp.xpath(".//td[4]/text()").extract()[0]).strip('\n')
    except:
    continue
    myposts.append(item)
    return myposts

问题:

它只给了我文本文件中提到的 url 的第一页输出。我想转到首页中下一步定义的页面的每个链接。

【问题讨论】:

  • 请修正你的缩进。
  • alecxe,我的编辑器(pycharm)中的缩进是正确的,它在stackoverflow中复制时唯一的错误

标签: python web-scraping scrapy forum


【解决方案1】:

改为定义start_requests() method:

def start_requests(self):
    with open('./myurls.txt','r') as f:
        for url in f:
            url = url.strip()
            yield scrapy.Request(url)

而且,您需要将 rules 定义为可迭代对象。另外,allow 中的正则表达式应该允许多个单个数字(\d+ 而不是\d):

rules = [
    Rule(SgmlLinkExtractor(allow='/user/\d+/track', restrict_xpaths='//li[@class="pager-next"]', canonicalize=False),
         callback='parse_page',
         follow=True)
]

【讨论】:

  • 方法 parse_page 没有被调用。当我替换它时,它会解析,然后只完成抓取,并且只有文件中 url 的第一页。 (正如 scrapy 文档中提到的,我们不应该对 CrawlSpider 使用 parse 方法,所以我避免了)你的 start_requests 函数也不起作用。
  • 感谢您更新代码。但它只适用于第二页。所有网址的第一页都被跳过了......我错过了什么吗???
  • @LearnByExample 会不会是首页没有链接?谢谢。
  • 亲爱的@alecxe,第一页有链接,您可以使用firefox检查drupal.org/user/3178461/track的第一页中是否有链接//li[@class="pager-next"]'检查 Firepath 的功能...
  • @LearnByExample 这就是我的意思 - 我在页面中收到“没有可用的内容”。
猜你喜欢
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2017-09-29
  • 2021-04-25
  • 1970-01-01
相关资源
最近更新 更多