Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 刮擦规则与正则表达式_Python_Regex_Scrapy - Fatal编程技术网

Python 刮擦规则与正则表达式

Python 刮擦规则与正则表达式,python,regex,scrapy,Python,Regex,Scrapy,我正在尝试使用Scrapy从geonames.org中删除信息。更具体地说,我想检索每个国家的10个最大城市。我的起始URL是。在本页中,我希望跟踪符合正则表达式的每个URL: /countries/\w{2}/.html 然后在随后的页面(即国家/地区页面)上,我希望使用以下结构跟踪URL-YYYY.html中的最大城市 其中,XX是两个字母的国家代码,YYYY是国家的实际名称,显然可以是可变长度的。下面的代码不起作用。我怀疑这是因为第二条规则的正则表达式有问题。但也许不是 from scra

我正在尝试使用Scrapy从geonames.org中删除信息。更具体地说,我想检索每个国家的10个最大城市。我的起始URL是。在本页中,我希望跟踪符合正则表达式的每个URL:

/countries/\w{2}/.html

然后在随后的页面(即国家/地区页面)上,我希望使用以下结构跟踪URL-YYYY.html中的最大城市 其中,XX是两个字母的国家代码,YYYY是国家的实际名称,显然可以是可变长度的。下面的代码不起作用。我怀疑这是因为第二条规则的正则表达式有问题。但也许不是

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
import re
import os

class MySpider(CrawlSpider):
    name = 'geocodeSpider'
    allowed_domains = ['www.geonames.org']
    start_urls = ['http://www.geonames.org/countries/']

    fileName="largest_cities.txt"    
    try:
        os.remove(os.path.join('geocode/output',fileName))
    except OSError:
        pass
    rules = (
        Rule(LinkExtractor(allow=(r'/countries/\w{2}/.\.html', )),),
        Rule(LinkExtractor(allow=(r'/\w{2}/largest-cities-in-.\.html', )), callback='parse_item'),
  )


    def parse_item(self, response):
...

正则表达式中的
只匹配一个字符,因此只有当YYYY是单个字符时,两个正则表达式才能工作。您可能希望将这些
替换为
+
\w+
或类似内容。