【发布时间】:2019-03-11 23:18:19
【问题描述】:
我正在尝试抓取此页面:
https://www.coolblue.nl/en/our-assortment
我成功地抓取了每个类别部分中的几乎所有链接。但是由于某种原因,所有这些“更多..”链接都没有通过,即使它们的 Xpath 应该与其他链接相同。
What I looked for in my inspector
我目前正在做的是寻找属于“a”标签的所有“href”值,类值category-navigation--link
我在 Python 上使用 Scrapy,所以我从脚本中获取信息的方式是:
response.xpath("//a[@class='category-navigation--link']/@href")
这很好地提供了页面中的大多数链接,除了这些“更多..”链接,但我不明白为什么。他们似乎和其他人一样,但是 xpath 选择器不知何故无法获取信息..
编辑:这是我的代码。它应该像这里发布的漂亮汤示例 PS1212 一样工作,唯一的区别是我返回链接。由于某种原因,它错过了所有“更多..”元素的 href 字段中的所有这些 url..
import scrapy
from ..items import CoolBlueItems
class QuoteSpider(scrapy.Spider):
name = "coolblue2"
start_urls = ["https://www.coolblue.nl/en/our-assortments]
def __init__(self):
self.declare_xpath()
def declare_xpath(self):
self.getAllSubCategoriesUrlsXpath = "//a[@class='category-navigation--link']/@href"
def parse(self, response):
item = CoolBlueItems()
urls_list = []
no_scrape_urls = ["/en/promotion", "/en/second-chance", "/en/gift-cards", "/en/coolblue-fan-products", "/en/all-brands"]
for Urls in response.xpath(self.getAllSubCategoriesUrlsXpath).getall():
current_url = Urls.strip()
if current_url not in urls_list and current_url not in no_scrape_urls and current_url.count("/") == 2:
urls_list.append(current_url)
item["Url"] = response.urljoin(current_url)
yield item
我遵循了 PS1212 的建议。不得不进行一些修改,因为它抛出了与处理信息的方式相关的错误。功能:
import scrapy
from ..items import CoolBlueItems
class QuoteSpider(scrapy.Spider):
name = "coolblue2"
start_urls = ["https://www.coolblue.nl/en/our-assortments]
for a in response.css("a.category-navigation--link::attr('href')").getall():
item["Url"] = re.split('/', a)
yield item
它仍然会跳过我想要的那个元素。以下是输出的第一个条目:
Category,CurrentPrice,OriginalPrice,Title,Url
,,,,",en,laptops"
,,,,",en,laptops,apple-macbook"
,,,,",en,desktops"
,,,,",en,monitors"
,,,,",en,keyboards"
编辑:问题出在选择器本身。我可以让我的脚本工作,但我仍然很好奇为什么 CSS 选择器工作而 xpath 不工作。这是我所做的一个测试,我使用 xpath 和 css 来从“a”部分中抓取具有特定类的所有元素:
>>> response.xpath("//a[@class='category-navigation--link']")[4].getall()
['<a class="category-navigation--link" href="/en/keyboards" rel="nofollow">\n Keyboards\n </a>']
>>>
>>> response.css('a.category-navigation--link')[4].get()
'<a class="category-navigation--link category-navigation--link--black" href="/en/laptops-desktops-monitors" data-trackclickevent="Homepage categor
y navigation|Computers & tablets|More..">\n More..\n
</a>'
如您所见,数组的第 5 个元素(两种情况下的索引 4)返回不同的值。我一定是在我的 Xpath 选择器的某个地方出错了。
【问题讨论】:
-
向我们展示您正在使用的代码以及您获得的结果。说“它以某种方式无法获取信息”并不能告诉我们太多。