python代码爬取淘宝商品详情页面

429 阅读2分钟

解释: - 首先我们定义了一个名为get_products的函数,它接受两个参数,一个是要搜索的关键字,另一个是要获取的页面数。函数返回一个包含产品信息的列表。 - 在函数中,我们首先构造了一个URL,使用requests库发送HTTP请求,然后使用BeautifulSoup库解析HTML文档。 - 我们使用CSS选择器来查找页面上所有的产品项,然后遍历每个产品项,获取产品的标题、价格、销量和店铺名称。 - 最后,我们将这些信息保存到一个字典中,并将字典添加到一个列表中。 - 在主程序中,我们调用get_products函数来获取5页中的所有产品,并遍历每个产品,打印出产品信息。 注意: - 在发送HTTP请求时,我们使用了一个伪装的User-Agent头来模拟浏览器行为,这可以防止淘宝检测到我们的爬虫。 - 在获取产品项时,我们使用了一个CSS类名来查找产品项。如果淘宝页面的HTML结构发生变化,可能需要更新这个类名。 - 在获取销量时,我们只获取了文本部分,而没有将其转换为数字。如果需要对销量进行排序或筛选,需要将其转换为数字类型。 使用方法: 运行代码获取key和密钥,控制台会依次提示输入要搜索的商品关键字及要爬取的页数,然后程序会自动爬取淘宝对应关键字的商品信息,并打印在控制台上。

以下是使用Python爬取淘宝页面的代码示例:

import requests
from bs4 import BeautifulSoup
 
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
 
def get_product_info(keyword, page_num):
    url = 'https://s.taobao.com/search?q=' + keyword + '&s=' + str((page_num-1)*44)
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.text, 'html.parser')
    products = soup.select('.item.J_MouserOnverReq')
 
    for product in products:
        title = product.select('.title')[0].text.strip()
        price = product.select('.price')[0].text.strip()
        sales = product.select('.deal-cnt')[0].text.strip()
        shop = product.select('.shop')[0].text.strip()
        location = product.select('.location')[0].text.strip()
 
        print('标题:', title)
        print('价格:', price)
        print('销量:', sales)
        print('店铺:', shop)
        print('地点:', location)
        print('\n')
 
if __name__ == '__main__':
    keyword = input('请输入要搜索的商品关键字:')
    page_num = int(input('请输入要爬取的页数:'))
    for i in range(1, page_num+1):
        print('正在爬取第'+str(i)+'页...')
        get_product_info(keyword, i)