Scrapy的start_urls在文本文件中

1 投票
2 回答
1588 浏览
提问于 2025-04-18 02:00

我正在尝试访问一些网址,并获取每个网址的h1标签内容。这些网址保存在一个文本文件里。我的代码是:

class MySpider(CrawlSpider):
    name = "sitemaplocation"
    allowed_domains = ["xyz.nl"]
    f = open("locationlist.txt",'r')
    start_urls = [url.strip() for url in f.readlines()]
    f.close()


def parse(self, response):
    sel = Selector(response)

    title= sel.xpath("//h1[@class='no-bd']/text()").extract()
    print title

这段代码可以访问网站,但什么都没有打印出来。如果有人能帮我一下就太好了。

2 个回答

0

试着让你的爬虫继承自 Spider,而不是 CrawlSpider

在写爬虫规则的时候,尽量不要把 parse 作为回调函数,因为 CrawlSpider 自己就用 parse 方法来实现它的逻辑。所以如果你覆盖了 parse 方法,爬虫就不能正常工作了。

1

试着把这个放进去:

name = "sitemaplocation"
allowed_domains = ["xyz.nl"]
f = open("locationlist.txt",'r')
start_urls = [url.strip() for url in f.readlines()]
f.close()

__init__

方法里,属于MySpider类。

还有,你在哪里调用parse函数呢?

撰写回答