【爬虫】Python爬取电商平台评论完整代码


更新:这是2020年的参数,已经不能直接使用。


利用Ajax爬取淘宝评论,这里完整的补充一下,包括数据存储。
对于Ajax参数的分析,Python爬取平台评论,这篇文章分析过了这里不再重复了。
主要是完善一下代码。

import time
import requests
import csv
import json
import os
import random
class taobaoSpider_content():
	"""通过分析网址的Ajax获取淘宝商品评论

	其中get_page方法是构造出url并且返回json格式的文本数据,get_cotent
	方法用于提取数据并返回一个生成器,最后main方法整合输出结果
	Attributes: itemId:商品ID
	Attributes:currentPage:评论页码
	Attributes:sellerId:淘宝商家Id
	"""
    def __init__(self,itemId,sellerId,currentPage):
        self.currentPage=currentPage
        self.url="https://rate.tmall.com/list_detail_rate.htm?"
        self.headers={
        			  "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400",
                      "referer":"https://detail.tmall.com/item.htm",
                      "Cookie":'自己的Cookie'
                     }
        self.itemId=itemId
        self.sellerId=sellerId

    def get_page(self):
        t_param=time.time()
        t_list=str(t_param).split(".")
        params={    "sellerId":self.sellerId,
                    "itemId":self.itemId,
                    "callback":str(int(t_list[1][3:])+1),
                    "_ksTS":t_list[0]+t_list[1][:3]+"_"+t_list[1][3:],
                    "currentPage":self.currentPage
                        }
        res=requests.get(self.url,params=params,headers=self.headers)
        try:
            if res.status_code==200:
                res=requests.get(self.url,params=params,headers=self.headers).text[len(t_list[1][3:])+3:-1]
                res_json=json.loads(res)
                res_str=json.dumps(res_json,indent=4)
                return json.loads(res_str)
        except:
            return None
    def get_content(self,json_data):
        if json_data!=None:
            for item in json_data.get("rateDetail").get("rateList"):
                content_time=item.get("rateDate")
                content_type=item.get("auctionSku")
                content_name=item.get("displayUserNick")
                content_data=item.get("rateContent")
                yield {
                        "content_time":content_time,
                        "content_type":content_type,
                        "content_name":content_name,
                        "content_data":content_data,
                        }
        else:
            print("该页出错啦!")
            return None
    def write_txt(self,data):
    """这是将结果写入txt文本文档的格式

	   将字典写入文本文档首先要利用json.dumps()转换成字符串格式.
	   json.dumps的indent参数是为了美化输出
	   json.ensure_ascii参数将数据输出程中文,同时要规定文件输出编码为utf-8
    """
        with open("taobaocontent.txt","a",encoding="utf-8") as file:
            file.write(json.dumps(data,indent=2,ensure_ascii=False))
            file.write("\n")
    
    def write_csv(self,data):
    """这是将结果写入csv文件

	   将字典直接写入csv需要用到csv模块。具体可以参考相关文档
	   这里要注意写入csv容易出现中文乱码,需要加encoding和newline参数。
    """
        with open("taobaocontent.csv","a",encoding="utf-8-sig",newline='') as file:
            fieldnames=["content_time","content_type","content_name","content_data"]
            writer=csv.DictWriter(file,fieldnames=fieldnames)
            writer.writerow(data)
    def main(self):
        json_data=self.get_page()
        self.get_content(json_data)
        return self.get_content(json_data)
        
if __name__=="__main__":
    for i in range(1,2):
		new_data=taobaoSpider_content(itemId=602210068322,sellerId=2616970884,currentPage=i)
        if new_data.main()!=None:
            for items in new_data.main():
                new_data.write_txt(items)
        else:
            pass
        time.sleep(random.randint(5,10))    #设置延时防止爬虫被封
    

以上代码已成功运行,如有错误,烦请告知,谢谢!

### 使用Python进行电商平台网页数据抓取的方法 #### 选择合适的工具和技术栈 对于电商网站的数据抓取,可以采用多种技术组合来完成任务。常用的技术包括: - **Requests**:用于发起HTTP请求并接收响应,适合静态页面的内容获取[^1]。 - **BeautifulSoup**:专注于HTML和XML文档的解析,能够方便地从复杂的结构化文本中抽取所需的信息[^3]。 - **Selenium**:当面对JavaScript渲染后的动态内容时尤为有用;它允许自动化浏览器操作,模拟真实用户的交互过程,从而访问那些仅在用户动作触发后才显示出来的信息[^2]。 - **pandas** 和其他数据处理库:帮助整理、清理所收集到的数据,并支持将其保存至文件系统或导入数据库以便进一步分析。 #### 实现基本功能 下面是一个简单的例子,展示了如何利用上述提到的一些工具构建一个基础版的商品详情页爬虫: ```python import requests from bs4 import BeautifulSoup import pandas as pd def fetch_product_details(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', } response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") product_info = {} try: title_element = soup.find('h1', class_='product-title') price_element = soup.find('span', id='priceblock_ourprice') if title_element and price_element: product_info['title'] = title_element.string.strip() product_info['price'] = float(price_element.string.replace('$', '').strip()) except AttributeError: pass return product_info if __name__ == "__main__": url = input("Enter the URL of a product page:") details = fetch_product_details(url) df = pd.DataFrame([details]) print(df.to_string(index=False)) ``` 这段代码定义了一个名为`fetch_product_details()` 的函数,该函数接受产品页面链接作为参数,并返回包含标题和价格的产品字典对象。如果成功找到这两个元素,则会创建一个新的DataFrame实例并将单个产品的信息转换成表格形式打印出来。 请注意,在实际应用中还需要考虑更多因素,比如错误处理机制、反爬措施规避策略等。此外,由于不同平台的具体实现可能有所差异,因此具体的标签名称可能会有所不同,需根据实际情况调整查找逻辑。
评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值