使用Selenium web驱动程序获取产品名称时发生InvalidSelector错误



我正试图在电子商务页面上获取产品的名称和价格。我正在使用Selenium,我的代码是:

for element in WebDriverWait(self.driver, 30).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, '.product-iWrap'))):
product_name_tmall = element.find_element_by_css_selector('.productTitle a')
product_price_tmall = element.find_element_by_css_selector('.productPrice em::text')
tmallSpider.items['product_name_tmall'] = product_name_tmall
tmallSpider.items['product_price_tmall'] = product_price_tmall
yield tmallSpider.items

当我运行时,它会给我这个错误

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified

我之前使用了相同css选择器的scrapy,它产生了正确的信息:

product_info = response.css('.product-iWrap')
for product in product_info:
product_name_tmall = product.css('.productTitle a').xpath('normalize-space(.)').get()
product_price_tmall = product.css('.productPrice em::text').extract()
tmallSpider.items['product_name_tmall'] = product_name_tmall
tmallSpider.items['product_price_tmall'] = product_price_tmall
product_detail_link = 'http:' + product.css('a::attr(href)')[0].extract()
yield scrapy.Request(product_detail_link, callback=self.start_scraping)

我不知道为什么css路径在Selenium中不起作用。页面的HTML为:

<div class="product-iWrap">
<p class="productPrice">
<em title="6599" data=spm-anchor-id="a220m.1000858.100725 ..." class>...</em>
</p>
<p class="productTitle">
<a href="//detail.tmall..." target="blank" title="iPad Air 3"...>...</a>
</p>
</div>

对于这个产品,我想得到6599和iPad Air 3,我想在第一页上显示所有产品的信息。知道怎么做吗?这是页面的URL:https://list.tmall.com/search_product.htm?q=ipad

您试图使用无效的CSS选择器。::text伪选择器不是任何实际CSS规范的一部分。Scrapy支持不属于CSS标准的选择器是可能的,甚至是可能的。jQuery过去也这样做,非标准的选择器支持给Selenium用户带来了不小的困惑,因为Selenium只支持浏览器原生选择器引擎支持的那些CSS部分。

顺便说一句,如果你使用的是CSS选择器,但你不确定它是否正确,你可以打开浏览器的开发工具,然后转到它的JavaScript控制台。键入document.querySelector("<put your selector here>"),然后按enter键。如果语句返回一个元素,那么您应该能够在Selenium代码中使用选择器。如果没有,你将无法成功使用它。

在这种特定情况下,我会做如下操作:

for element in WebDriverWait(self.driver, 30).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, '.product-iWrap'))):
product_name_tmall = element.find_element_by_css_selector('.productTitle a')
product_price_tmall = element.find_element_by_css_selector('.productPrice em')
tmallSpider.items['product_name_tmall'] = product_name_tmall.get_attribute('title')
tmallSpider.items['product_price_tmall'] = product_price_tmall.get_attribute('title')
yield tmallSpider.items

最新更新