【发布时间】:2020-08-11 18:50:44
【问题描述】:
简介
在使用scrapy 几个星期之后,我仍然有一些问题,要弄清楚,一些xpath 表达式。 大多数情况下,我在提取表格数据和“ul 和 li”标签时遇到了大问题。
示例 我尝试获取以下数据的网页: https://www.karton.eu/460x310x160-mm-Postal-Shipping-Box
有一个名为:“Productdata”的表,我需要每一行,但我没有得到它。
我试过类似的东西:
response.xpath('//*[@id="2"]/tr/td/text()').getall(),
response.xpath('//table[@class="table table-striped"]/tr/td/text()').getall()
我的代码
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from ..items import KartoneuItem
import csv
class KartoneuSpider(scrapy.Spider):
name = "karton13"
allowed_domains = ['karton.eu']
with open("kartonsalllinks.csv","r") as f:
reader = csv.DictReader(f)
start_urls = [items['Link'] for items in reader]
rules = (
Rule(LinkExtractor(), callback='parse'),
)
def parse(self, response):
card = response.xpath('//div[@class="product-info-inner"]')
if not card:
print('No productlink', response.url)
for a in card:
items = KartoneuItem()
items['SKU'] = a.xpath('.//span[@class="art_nr"]/strong/text()').get()
items['Title'] = a.xpath('.//h1[@class="fn product-title"]/text()').get()
items['Link'] = a.url
items['Price'] = a.xpath('.//div[@class="price_wrapper"]/strong/text()').get()
items['Delivery_Status'] = a.xpath('.//div[@class="col-lg-4"]/span/text()').get()
items['Desc'] = a.xpath('.//*[@id="1"]/p/text()').getall()
items['Breadcrumb'] = a.xpath('.//*[@id="breadcrumb"]/li/a/@href').getall()
yield items
我已经有一个包含域的每个链接的 .csv 文件,现在上面的代码应该打开每个链接,检查它是否是产品链接(response.xpath('//div[@class="product-info-inner"]')没有该标签的页面,应该跳过,因为它们例如可以是类别链接。
【问题讨论】:
标签: python html web xpath scrapy