如何使用scrapy框架循环爬京东数据后导入Mysql的方法

零到壹度
发布: 2018-03-30 10:20:23
原创
2131人浏览过

本文主要为大家分享一篇J如何使用scrapy框架循环爬京东数据后导入Mysql的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧,希望能帮助到大家。

京东是有反爬机制的,所以我用到用户代理、伪装成浏览器。

爬取数据是京东商城的手机信息 url:https://list.jd.com/list.html?cat=9987,653,655&page=1

大概是9000多条数据,不在列表之内的商品没有算在内。

遇到的问题:

1、用户代理最好是用方法(use_proxy)封装起来,因为自己之前就是把代码直接写在parse下,遇到not enough values to unpack的问题,我实在不知道错误出在哪一句,就每句代码之后print,发现问题出在urlopen(),但是我反复试、查网上,也没发现错误在哪,写成方法就解决了,现在想来可能是因为parse方法是处理respose。

2、在把数据导入mysql之前,我先试着把数据导入到文件中,但是在导入中,发现x.txt的大小一直是0kb,1kb在变,没有增长,想想应该是覆盖了,本来是认为自己fh.close()写的位置不对,后来突然想到

京点点
京点点

京东AIGC内容生成平台

京点点 26
查看详情 京点点

fh = open("D:/pythonlianxi/result/4.txt", "w")写错了,应该要把'w'变成'a'。

3、导入数据库,碰到的问题主要是中文编码问题,要先打开mysql,  show variables like '%char%';查看数据库的字符集编码形式,用对应的形式,比如我自己是utf8,用gbk就不好使。另外,在写连接mysql时 charset='utf8'不要忘记。

下面是具体代码:

<span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 16px;">conn = pymysql.connect(host="127.0.0.1", user="root", passwd="root", db="jingdong", charset="utf8")<br/></span>
登录后复制

<span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 16px;">import scrapy<br/>from scrapy.http import Request<br/>from jingdong.items import JingdongItem<br/>import re<br/>import urllib.error<br/>import urllib.request<br/>import pymysql<br/>class JdSpider(scrapy.Spider):<br/>    name = 'jd'   <br/>    allowed_domains = ['jd.com']    <br/>    #start_urls = ['http://jd.com/']    <br/>     header = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"} <br/>         #fh = open("D:/pythonlianxi/result/4.txt", "w")    <br/>         def start_requests(self):      <br/>             return [Request("https://list.jd.com/list.html?cat=9987,653,655&page=1",callback=self.parse,headers=self.header,meta={"cookiejar":1})]   <br/>              def use_proxy(self,proxy_addr,url):       <br/>               try:<br/>            req=urllib.request.Request(url)<br/>            req.add_header("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36")<br/>            proxy = urllib.request.ProxyHandler({"http": proxy_addr})<br/>            opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)<br/>            urllib.request.install_opener(opener)<br/>            data=urllib.request.urlopen(req).read().decode("utf-8","ignore")           <br/>             return data      <br/>       except urllib.error.URLError as e:         <br/>          if hasattr(e,"code"):                <br/>             print(e.code)            <br/>          if hasattr(e,"reason"):               <br/>             print(e.reason)        <br/>          except Exception as e:        <br/>             print(str(e))   <br/>              <br/>    def parse(self, response):<br/>        item=JingdongItem()<br/>        proxy_addr = "61.135.217.7:80"    <br/>      try:<br/>            item["title"]=response.xpath("//p[@class='p-name']/a[@target='_blank']/em/text()").extract()<br/>            item["pricesku"] =response.xpath("//li[@class='gl-item']/p/@data-sku").extract()            <br/>            <br/>            for j in range(2,166):<br/>                url="https://list.jd.com/list.html?cat=9987,653,655&page="+str(j)               <br/>                 print(j)                <br/>                 #yield item               <br/>                  yield Request(url)<br/>            pricepat = '"p":"(.*?)"'          <br/>              personpat = '"CommentCountStr":"(.*?)",'            <br/>              print("2k")            <br/>              #fh = open("D:/pythonlianxi/result/5.txt", "a")            <br/>              conn = pymysql.connect(host="127.0.0.1", user="root", passwd="root", db="jingdong", charset="utf8")              <br/>              <br/>         for i in range(0,len(item["pricesku"])):<br/>                priceurl="https://p.3.cn/prices/mgets?&ext=11000000&pin=&type=1&area=1_72_4137_0&skuIds="+item["pricesku"][i]<br/>                personurl = "https://club.jd.com/comment/productCommentSummaries.action?referenceIds=" + item["pricesku"][i]<br/>                pricedata=self.use_proxy(proxy_addr,priceurl)<br/>                price=re.compile(pricepat).findall(pricedata)<br/>                persondata = self.use_proxy(proxy_addr,personurl)<br/>                person = re.compile(personpat).findall(persondata)<br/>         <br/>                title=item["title"][i]               <br/>                print(title)<br/>                price1=float(price[0])                <br/>                #print(price1)                <br/>                person1=person[0]<br/>                #fh.write(tile+"\n"+price+"\n"+person+"\n")                <br/>                cursor = conn.cursor()<br/>                sql = "insert into jd(title,price,person) values(%s,%s,%s);"               <br/>                params=(title,price1,person1)                <br/>                print("4")<br/>                cursor.execute(sql,params)<br/>                conn.commit()            <br/>                <br/>                #fh.close()<br/></span>
登录后复制
<span style="font-family: 微软雅黑, "Microsoft YaHei"; font-size: 16px;">                conn.close()            <br/>                return item        <br/>                except Exception as e:            <br/>                print(str(e))</span><span style="font-family: 微软雅黑, "Microsoft YaHei";"><br/></span>
登录后复制

相信聪明的你已经学会了,还等什么,赶快去实践吧。


以上就是如何使用scrapy框架循环爬京东数据后导入Mysql的方法的详细内容,更多请关注php中文网其它相关文章!

相关标签:
京东
京东

京东app是一款移动购物软件,具有商品搜索/浏览、评论查阅、商品购买、在线支付/货到付款、订单查询、物流跟踪、晒单/评价、返修退换货等功能,为您打造简单、快乐的生活体验。有需要的小伙伴快来保存下载体验吧!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号