求Python BeautifulSoup爬取数据不能正常运行源码修正,,#coding=utf-
求Python BeautifulSoup爬取数据不能正常运行源码修正,,#coding=utf-
#coding=utf-8from __future__ import print_functionfrom bs4 import BeautifulSoupimport urllib2import sysimport stringreload(sys)sys.setdefaultencoding("gbk")filename="top500.csv"f=open(filename,'w')f.write('num,name,country,address,indroduce'+'\n')a=1for ye in range(0,20): url="http://www.alexa.com/topsites/global;"+str(ye) page=urllib2.urlopen(url) soup=BeautifulSoup(page) nameLists=soup.findAll(attrs={"class":"site-listing"}) for names in nameLists: name=names.find('a').text print(name) siteUrl="http://www.alexa.com/siteinfo/"+name ipUrl="http://www.ip.cn/index.php?ip=www."+name print(siteUrl) #获取网站所在国家 pageSite=urllib2.urlopen(siteUrl) soup=BeautifulSoup(pageSite) titleLists=soup.findAll(attrs={"class":"metrics-title"}) country=titleLists[1].find('a').text print(country) #获取网站服务器所在位置 ipSite=urllib2.urlopen(ipUrl) soup=BeautifulSoup(ipSite) addressList=soup.find(attrs={"class":"well"}) addresses=addressList.findAll('p') address=addresses[1].text address=address.replace(',',' ')#替换掉',' print(address) name1="www."+name print(name1) introduce=names.find(attrs={"class":"description"}).text introduce=introduce.replace('... More','') introduce=introduce.replace(',','.')#替换掉',' paiming=str(a) f.write(paiming+','+name+','+country+','+address+','+introduce.encode('gbk','ignore')+'\n') a=string.atoi(paiming)+1f.close()print("\nover")
贴出代码,爬到第四个数据就爬不动了,光标一直闪没有继续下去,请教一下是因为打开的url太多了么,并且有循环嵌套,不是的话是什么原因呢,说明一下我的是10M宽带应该不是网速的问题吧。
应该是网络问题吧。我这边试了一下,每次执行了几个就连接超时了。
发现了几个小问题:
在urlopen 那里设置一下超时时间 for 循环后面加个time.sleep(1) 吧 这样就避免超时了
我测试了一下没发现问题。
编橙之家文章,
相关内容
- python爬虫抓取相关的小白问题,python爬虫抓取小白,大神
- Python字典与json数据好像为什么呢?,python字典json数据
- JetBrains家的IDE如何使用会更高效,jetbrains更高效,装了
- python想生成linux命令行可用软件应该如何做打包,pyth
- 原理相同只是精简了的python代码,运行结果不同是为什么
- Python擅长处理特别大的文件吗,python擅长处理,Python处理
- 新手Python算法统计list及tuple应用有什么好方法,python
- django较多数据传递如何优雅的呈现,django较多传递,最近
- 不用跳转方法如何实现手机站与pc站之间的无缝切换,
- python3中文输出报UnicodeEncodeError错误,如何解决,,代码
评论关闭