python爬虫 - 使用python和beautifulSoup爬数据,爬到第三条就爬不动了

 给彼此祝福_完美旳谢幕_835 发布于 2022-11-05 18:01
#coding=utf-8
from __future__ import print_function
from bs4 import BeautifulSoup
import urllib2
import sys
import string
reload(sys)
sys.setdefaultencoding("gbk")
filename="top500.csv"
f=open(filename,'w')
f.write('num,name,country,address,indroduce'+'\n')
a=1
for 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)+1
f.close()
print("\nover")

贴出代码,爬到第四个数据就爬不动了,光标一直闪没有继续下去,请教一下是因为打开的url太多了么,并且有循环嵌套,不是的话是什么原因呢,说明一下我的是10M宽带应该不是网速的问题吧。

4 个回答
  • 发现了几个小问题:

    1. 暴力爬虫是很容易被对方服务器探测并且屏蔽的,所以你这情况极有可能是短时间超过了服务器设置的阀值,然后在返回结果时候给你拖延或者直接403、404了

    2. 有时候卡在那不动,是因为beautifulsoup的解释器问题。你在实例化的时候应该(必须)指定解释器,一般是lxml,但是网页的话强烈推荐html5lib。这么用:soup = BeautifuSoup(html, 'html5lib')
      不过根据官方解释,你应该事先安装这几个解释器。pip install html5lib就装好了。

    2022-11-10 06:59 回答
  • 我测试了一下没发现问题。

    2022-11-10 07:02 回答
  • 应该是网络问题吧。我这边试了一下,每次执行了几个就连接超时了。

    2022-11-10 07:07 回答
  • 在urlopen 那里设置一下超时时间 for 循环后面加个time.sleep(1) 吧 这样就避免超时了

    2022-11-10 07:18 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有