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

来源:互联网 发布:淘宝商城有假货吗 编辑:程序博客网 时间:2024/04/29 03:59

学习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 0
原创粉丝点击