想问一下各位大佬,用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})
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
可以尝试使用正则表达式来匹配价格,举个例子:
import re
# 定义匹配规则
pattern = r'[\u4e00-\u9fa5]+元'
# 爬取商品价格
html = requests.get('https://s.taobao.com/search?q=商品名称')
soup = BeautifulSoup(html.content, 'html.parser')
items = soup.select('.J_MouserOnverReq')
# 提取价格
for item in items:
price = item.select_one('.J_CalcPrice').text
price = re.findall(pattern, price)[0]
print(price)