我正在尝试用spider.py从mysql表中选择一个来填充start_URL。当我运行“scriby run spider spider.py”时,我没有得到输出,只是它没有错误地完成。
我已经在python脚本中测试了select查询,并用mysql表中的条目填充了start_url。
蜘蛛.py

from scrapy.spider import BaseSpider
from scrapy.selector import Selector
import MySQLdb


class ProductsSpider(BaseSpider):
    name = "Products"
    allowed_domains = ["test.com"]
    start_urls = []

    def parse(self, response):
        print self.start_urls

    def populate_start_urls(self, url):
        conn = MySQLdb.connect(
                user='user',
                passwd='password',
                db='scrapy',
                host='localhost',
                charset="utf8",
                use_unicode=True
                )
        cursor = conn.cursor()
        cursor.execute(
            'SELECT url FROM links;'
            )
    rows = cursor.fetchall()

    for row in rows:
        start_urls.append(row[0])
    conn.close()

最佳答案

更好的方法是重写start_requests方法。
这可以查询您的数据库,很像populate_start_urls,并返回一系列Request对象。
您只需将populate_start_urls方法重命名为start_requests并修改以下行:

for row in rows:
    yield self.make_requests_from_url(row[0])

08-04 13:44