【发布时间】:2018-08-28 19:34:48
【问题描述】:
我需要使用正则表达式从多个 url 的脚本标签中提取数据。我已经设法实现了完成一半工作的代码。我有一个 csv 文件('links.csv '),其中包含我需要抓取的所有网址。我设法读取了 csv 并将所有 url 存储在名为 'start_urls' 的变量中。我的问题是我需要一种方法来一次读取来自'start_urls' 的网址并执行我的代码的下一部分。
当我在终端中执行我的代码时,我收到 2 个错误:
1.ERROR:获取启动请求时出错 2. TypeError: Request url must be str or unicode, got list
如何修复我的代码?我是 Scrapy 的初学者,但我真的需要这个脚本才能工作......提前谢谢你!
以下是我存储在初始 csv('links.csv') 中的一些 url 示例:
"https://www.samsung.com/uk/smartphones/galaxy-note8/"
"https://www.samsung.com/uk/smartphones/galaxy-s8/"
"https://www.samsung.com/uk/smartphones/galaxy-s9/"
这是我的代码:
import scrapy
import csv
import re
class QuotesSpider(scrapy.Spider):
name = "quotes"
def start_requests(self):
with open('links.csv','r') as csvf:
for url in csvf:
yield scrapy.Request(url.strip())
def parse(self, response):
source = response.xpath("//script[contains(., 'COUNTRY_SHOP_STATUS')]/text()").extract()[0]
def get_values(parameter, script):
return re.findall('%s = "(.*)"' % parameter, script)[0]
with open('baza.csv', 'w') as csvfile:
fieldnames = ['Category', 'Type', 'SK']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for pvi_subtype_name,pathIndicator.depth_5,model_name in zip(source):
writer.writerow({'Category': get_values("pvi_subtype_name", source), 'Type': get_values("pathIndicator.depth_5", source), 'SK': get_values("model_name", source)})
【问题讨论】: