selenium--爬虫爬取京东商城商品信息

本文分享了使用Selenium爬取京东商城商品信息的完整代码,包括搜索、翻页及商品信息抓取等功能,适用于Python爬虫初学者实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

selenium--爬虫爬取京东商城商品信息

说明

看完用selenium爬取淘宝商品信息的网课,于是乎想着自己也整一个selenium程序来爬取京东以作巩固。写了几个小时的代码,通过不断调试,学到了很多细节上的处理,完整代码在下方,使用时修改搜索的参数就可以开始爬取了,事先要安装goole chrome的驱动。最终爬取的结果存储在了products数组中,需要添加其他处理时,直接在程序最后使用数组来调用爬取的结果。运行结果不展示了,就是把信息输出出来,因为要等待网页加载,所以运行时间有点久。

完整代码

from selenium import webdriver
import time

def Search_Product(key):     #向搜索框输入内容    
    driver.find_element_by_id('key').send_keys(key)

def Click_Search():        #搜索按钮    
    driver.find_element_by_class_name('button').click()

def PageNum():         #获取总的页数    
    pagenum=driver.find_element_by_class_name('p-skip').text    
    return pagenum[1:-10]

def Page_Next():      #下一页    
    page=driver.find_element_by_class_name('pn-next')    
    page.click()    
    
if __name__=='__main__':    
    products=[]    
    count=0    
    url="http://www.jingdong.com/"    
    driver=webdriver.Chrome()    
    driver.get(url)    
    Search_Product('特仑苏')    
    driver.maximize_window()    
    Click_Search()    
    time.sleep(3)      #进程挂起3秒,等待窗口加载完成,未加载完成会导致爬取的数据不全,或者元素无法定位    
    driver.execute_script("window.scrollBy(0, 8000)")    #下拉滚动条以使网页中的全部商品信息加载,不下拉进度条,下半部分信息不显示    
    time.sleep(1)    
    while(count<int(PageNum())):          
          products_info=driver.find_elements_by_xpath('//div[@class = "gl-i-wrap"]')        
          for div in products_info:            
              name=div.find_element_by_xpath('.//div[@class="p-name p-name-type-2"]')     #商品名称            
              price=div.find_element_by_xpath('.//div[@class="p-price"]//i')           #价格            
              shop=div.find_element_by_xpath('.//div[@class="p-shop"]')  #店铺名称            
              commit=div.find_element_by_xpath('.//div[@class="p-commit"]//a')       #评价            
              products.append((name.text,price.text+'元',shop.text,commit.text+'评论'))            
          pagenum=count+1        
          print('第'+str(pagenum)+'页已提取,共'+PageNum()+'页')        
          Page_Next()        
          time.sleep(3)        
          driver.execute_script("window.scrollBy(0, 8000)")            
          time.sleep(1)        
          count+=1    
    driver.quit()    
    print(products)


### 获取京东商城商品详情的Python爬虫源码 为了实现对京东商城的商品详情页面的数据抓取,可以采用`requests`库配合正则表达式或BeautifulSoup解析网页内容。考虑到部分网站会检测自动化工具访问行为并采取反制措施,建议设置合理的请求头模拟浏览器环境,并遵守目标站点的服务条款。 下面是一个简单的基于`requests`和`lxml`库的例子来获取指定URL下的商品信息: ```python import requests from lxml import etree def fetch_product_info(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', # 可选地添加更多header字段以更好地伪装成真实用户的HTTP请求 } response = requests.get(url, headers=headers) if response.status_code != 200: raise Exception(f"Failed to load page {url}") html_content = response.text tree = etree.HTML(html_content) title = tree.xpath('//div[@class="sku-name"]/text()')[0].strip() price = ''.join(tree.xpath("//span[starts-with(@id,'jd-price')]/text()")) print(f'Title: {title}') print(f'Price: {price}') if __name__ == '__main__': product_url = "https://item.jd.com/your-product-id.html" try: fetch_product_info(product_url) except Exception as e: print(e) ``` 此脚本尝试从给定的产品链接中提取名称和价格两项基本信息[^3]。需要注意的是,实际应用时可能还需要处理诸如登录验证、验证码识别等问题;而且由于HTML结构可能会随时间变化而改变,因此XPath路径也需要相应调整。 对于动态加载的内容,则需考虑使用Selenium或其他支持JavaScript执行环境的方法来进行更复杂的交互操作[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值