想问一下各位铁铁,用xpath爬取淘宝商品价格,结果定位到价格这里是繁体字,没有数字。这种情况该如何爬取。
# 爬取当前页的内容
for row in range(1, 16): # 假设有15行,可以根据实际情况进行调整
for position in range(1, 5): # 每行有4个商品,可以根据实际情况进行调整
title_xpath = f'//*[@id="J_ShopSearchResult"]/div/div[3]/div[{row}]/dl[{position}]/dd[2]/a'
# 爬取商品价格
price_xpath = f'//*[@id="J_ShopSearchResult"]/div/div[3]/div[{row}]/dl[{position}]/dd[2]/div/div[1]'
img_xpath = f'//*[@id="J_ShopSearchResult"]/div/div[3]/div[{row}]/dl[{position}]/dt/a/img'
title_element = driver.find_element(By.XPATH, title_xpath)
price_element = driver.find_element(By.XPATH, price_xpath)
img_element = driver.find_element(By.XPATH, img_xpath)
title = title_element.text
price = price_element.text
img_url = img_element.get_attribute('src')
if title:
if not img_url.startswith(('http://', 'https://')):
img_url = 'https:' + img_url # 补全协议部分
item_list.append({'title': title, 'price': price, 'img_url': img_url})
【以下回答由 GPT 生成】
首先,要处理定位到的繁体字价格,我们可以使用Python的库来将繁体字转换为数字。下面是解决该问题的步骤:
opencc-python
,它可以用于繁体字转换成简体字。pip install opencc-python
from opencc import OpenCC
cc = OpenCC('t2s') # 创建一个从繁体到简体的转换实例
price_xpath
对应的元素上获得文本信息。price_element = driver.find_element_by_xpath(price_xpath)
price_text = price_element.text
simplified_price = cc.convert(price_text)
price = re.match(r'\d+', simplified_price).group()
item_list
列表中。item_list.append(price)
总结,以上是使用XPath爬取淘宝商品价格的步骤,并处理定位到的繁体字。完整的代码示例如下:
from selenium import webdriver
from opencc import OpenCC
import re
# 创建一个从繁体到简体的转换实例
cc = OpenCC('t2s')
# 启动WebDriver,访问页面
driver = webdriver.Chrome()
driver.get('http://example.com')
# 进行价格的爬取
price_element = driver.find_element_by_xpath(price_xpath)
price_text = price_element.text
# 将繁体字转换为简体字
simplified_price = cc.convert(price_text)
# 提取数字部分
price = re.match(r'\d+', simplified_price).group()
# 将价格添加到列表中
item_list.append(price)
# 关闭WebDriver
driver.quit()
请注意,以上代码只是示例,实际情况中你需要根据你的具体需求和页面结构来进行一些调整。如果你需要更多帮助,请提供更多细节或代码,并说明具体的问题所在。
【相关推荐】