289day(使用BeautifulSoup练习京东商品爬取)

本文介绍了一种使用Python中的BeautifulSoup库抓取京东网站商品信息的方法。通过构造请求头和参数,实现对特定关键词的商品搜索结果页面进行爬取,并解析出每个商品链接。

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

《2018年7月17日》【连续289天】

标题:使用BeautifulSoup练习京东商品爬取;

内容:

1.
 

import requests
from urllib.parse import urlencode
from bs4 import BeautifulSoup
from requests.exceptions import RequestException
 
 
def find_goods(page,s,keyword):
    params = {
        'keyword': keyword,
        'enc' :'utf-8',
        'qrst': '1',
        'rt': '1',
        'stop': '1',
        'vt' :'2',
        'wq' :keyword,
        'page':page,
        's':s,
        'click':'0',
        }
    url ='https://search.jd.com/Search?'+urlencode(params)
    headers ={'User-Agent':'User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1'}
    try:   
        response = requests.get(url, headers =headers)
        response.encoding="utf-8"
        if response.status_code == 200:
                return response
        return None
    except RequestException:
        return None
 
 
def print_goods(r):
    soup =BeautifulSoup(r.text,'lxml')
    so=soup.find(name='ul',attrs={"class":['gl-warp','clearfix']})
    for s in so.find_all(name='a'):
        print('http:'+s['href'])
    
def main(keyword):
    keyword=keyword
    page =1
    s =1
    for i in range(5):
        page +=2*i
        s +=53*i
        re =find_goods(page,s,keyword)
        print_goods(re)
 
if __name__ == "__main__":
    keyword="手表"
    main(keyword)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值