【发布时间】:2021-06-30 04:27:31
【问题描述】:
我正在尝试从给定存储在“数据”中的 url 列表的网站中抓取数据。
我注意到一些 url 没有“og_price”和“discount”的 xpath,我收到 NoSuchElement 错误,或者直接说“og_price”和“discount”未定义大概是因为某些 url 没有有那个 xpath。
我想检查 url 中是否存在 xpath(我试图用 try-except 来做)并返回一个空值或只是字符串“no”,但我被困在如何做到这一点上,因为我稍后会调用“ "og_price" 和 "discount" 上的 .text" 会说 'str' 对象没有属性 '.text'
for url in data:
driver.get(url)
item_name = driver.find_element_by_xpath('//span[@id="productTitle"]')
brand_name = driver.find_element_by_xpath('//*[@class="a-spacing-small"][.//*[contains(.,"Brand")]]/td[@class="a-span9"]/span')
price = driver.find_element_by_xpath('//div[@class="a-section a-spacing-micro"]/span[@id="price_inside_buybox"]')
try:
og_price = driver.find_element_by_xpath('//span[@class="priceBlockStrikePriceString a-text-strike"]')
discount = driver.find_element_by_xpath('//td[@class="a-span12 a-color-price a-size-base priceBlockSavingsString"]')
except NoSuchElementException:
og_price = null
discount = null
row = { 'Item Name': item_name.text,
'Brand Name': brand_name.text,
'Price': price.text,
'Original Price': og_price.text,
'URL': url
}
【问题讨论】:
标签: python python-3.x selenium web-scraping xpath