爬取大众点评黄焖鸡米饭的数据

学习python已经一段时间,就想着利用他爬取大众点评上的一些数据,用于分析。

这里,我选择爬取国内各个地区和省份关于黄焖鸡米饭的店面数据

具体的格式:店面 id,省份,城市,开店时间,店名

首先声明:

大众点评的数据,并不是很好爬取的。注意:他会禁止IP

我通过下面方法得以解决

1、UserAgent经常换一换;
2、访问时间间隔设长一点,访问时间设置为随机数;sleep()
3、访问页面的顺序也可以随机着来

4、自动IP代理

获取IP

User_Agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0'
header = {}
header['User-Agent'] = User_Agent
url = 'http://www.xicidaili.com/nn/1'
req = urllib2.Request(url,headers=header)
res = urllib2.urlopen(req).read()


soup = BeautifulSoup(res,'html.parser', from_encoding='utf-8')
ips = soup.findAll('tr')
f = open("proxy.txt","w")
for x in range(1,len(ips)):
    ip = ips[x]
    tds = ip.findAll("td")
    #ip_temp = tds[1].contents[0]+"\t"+tds[2].contents[0]+"\n"
    print tds[1].contents[0]+"\t"+tds[2].contents[0]
    f.write(tds[1].contents[0]+','+tds[2].contents[0]+'\n')


获取可以使用的IP

import urllib
import socket
import json
socket.setdefaulttimeout(3)
f = open("proxy.txt")
lines = f.readlines()
proxys = []
for i in range(0,len(lines)):
    ip = lines[i].replace('\n','').split(",")
    proxy_host = "http://"+ip[0]+":"+ip[1]
    proxy_temp = {"http":proxy_host}
    proxys.append(proxy_temp)
url = "http://ip.chinaz.com/getip.aspx"
index=1
fw=open('use_proxy.txt','w')
for proxy in proxys:
    print index
    try:
        res = urllib.urlopen(url,proxies=proxy).read()
        fw.write(json.dumps(proxy))
        print proxy
        index+=1
    except Exception,e:
        index+=1

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值