我已经创建了一个蜘蛛,它收集了具有匹配电话号码的公司名称列表。然后将其保存为CSV文件。
然后我想使用CSV文件中的电话号码作为POST数据从其他站点获取数据。我希望它循环遍历相同的起始URL,但只是抓取每个电话号码产生的数据,直到CSV文件中没有剩余数字。
这是我到目前为止所得到的:
from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.http import FormRequest
from scrapy.selector import HtmlXPathSelector
from scrapy import log
import sys
from scrapy.shell import inspect_response
from btw.items import BtwItem
import csv
class BtwSpider(BaseSpider):
name = "btw"
allowed_domains = ["siteToScrape.com"]
start_urls = ["http://www.siteToScrape.com/broadband/broadband_checker"]
def parse(self, response):
phoneNumbers = ['01253873647','01253776535','01142726749']
return [FormRequest.from_response(response,formdata={'broadband_checker[phone]': phoneNumbers[1]},callback=self.after_post)]
def after_post(self, response):
hxs = HtmlXPathSelector(response)
sites = hxs.select('//div[@id="results"]')
items = []
for site in sites:
item = BtwItem()
fttcText = site.select("div[@class='content']/div[@id='btfttc']/ul/li/text()").extract()
# Now we will change the text to be a boolean value
if fttcText[0].count('not') > 0:
fttcEnabled=0
else:
fttcEnabled=1
item['fttcAvailable'] = fttcEnabled
items.append(item)
return items
在我刚刚尝试通过列表(phoneNumbers)循环的那一刻,但到目前为止我还没有设法让它工作。一旦我知道如何做到这一点,我将能够让它自己从CSV文件中提取它。在当前状态下,它只是使用列表中索引为1的phoneNumber。
答案 0 :(得分:2)
假设您有一个带有电话的phones.csv
文件:
01253873647
01253776535
01142726749
这是你的蜘蛛:
import csv
from scrapy.item import Item, Field
from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.http import FormRequest
from scrapy.selector import HtmlXPathSelector
class BtwItem(Item):
fttcAvailable = Field()
phoneNumber = Field()
class BtwSpider(BaseSpider):
name = "btw"
allowed_domains = ["samknows.com"]
def start_requests(self):
yield Request("http://www.samknows.com/broadband/broadband_checker", self.parse_main_page)
def parse_main_page(self, response):
with open('phones.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
phone_number = row[0]
yield FormRequest.from_response(response,
formdata={'broadband_checker[phone]': phone_number},
callback=self.after_post,
meta={'phone_number': phone_number})
def after_post(self, response):
hxs = HtmlXPathSelector(response)
sites = hxs.select('//div[@id="results"]')
phone_number = response.meta['phone_number']
for site in sites:
item = BtwItem()
fttc = site.select("div[@class='content']/div[@id='btfttc']/ul/li/text()").extract()
item['phoneNumber'] = phone_number
item['fttcAvailable'] = 'not' in fttc[0]
yield item
以下是运行后刮掉的内容:
{'fttcAvailable': False, 'phoneNumber': '01253873647'}
{'fttcAvailable': False, 'phoneNumber': '01253776535'}
{'fttcAvailable': True, 'phoneNumber': '01142726749'}
想法是使用start_requests
抓取主页,然后在回调中逐行读取csv文件,为每个电话号码读取yield
新Requests
(csv行) )。另外,通过phone_number
字典将meta
传递给回调,以便将其写入Item
字段(我认为您需要这样来区分项目/结果)。
希望有所帮助。