Python 爬虫 程序跑不动了

xiaoben9 2016-10-23 08:34:14
大家好!我今天在用Python写爬虫程序的时候遇到了一个问题,
我程序的思路是这样:首先从一个 txt文件 中读取关键词,然后以这个关键词为条件在搜索引擎(百度)中搜索结果,将每次搜索的页面获取后利用正则表达式获取自己想要的内容。
问题是:txt文件 的前几行是可以搜索出来并利用正则获取结果,但是有时候txt文件的后面几行就没反应了,但是有时候又是可以搜索出来结果的,有时候还会出现 httplib error啥的,感觉很郁闷。
请问各位这是什么情况呢?是不是哪里的参数没有设置呢?下面是我的源码:
user_agent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"
headers = {"User-Agent":user_agent}
baseUrl = 'http://www.baidu.com/s'
word = search_str #搜索关键词
data = {'wd':word}
data = urllib.urlencode(data)
url = baseUrl+'?'+data
#伪装浏览器——加一个 user-agent
try :
qingqiu = urllib2.Request(url,headers=headers);
xaingying = urllib2.urlopen(qingqiu)
#筛选:
items = re.findall('(百度为您找到相关结果约)([0-9].*?)(个)',xaingying.read(), re.S)
for item in items:
str = item[1];
num = int(str.replace(',', ''),10)
if num >= 10000:
return num
else:
continue
# print xaingying.read()
except urllib2.URLError,e:
if hasattr(e,"code"):
print e.code
if hasattr(e,"reason"):
print e.reason


这是结果截图:
...全文
952 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
riding 2016-11-15
  • 打赏
  • 举报
回复
用scrapy ,很好用,你自己写的啥时候去!
nieoding 2016-10-31
  • 打赏
  • 举报
回复
妹子头像好萌
屎克螂 2016-10-27
  • 打赏
  • 举报
回复
user_agent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"
headers = {"User-Agent":user_agent}
baseUrl = 'http://www.baidu.com/s'
word = search_str #搜索关键词
data = {'wd':word}
data = urllib.urlencode(data)
url = baseUrl+'?'+data
#伪装浏览器——加一个 user-agent
try :
    qingqiu = urllib2.Request(url,headers=headers);
    xaingying = urllib2.urlopen(qingqiu, timeout=10)    #设置超时时间
    #筛选:
    items = re.findall('(百度为您找到相关结果约)([0-9].*?)(个)',xaingying.read(), re.S)
    for item in items:
        str1 = item[1]; #str是关键字最好不要用它做变量名
        num = int(str1.replace(',', ''),10)
        if num >= 10000:
            return num
        else:
            continue
        #     print xaingying.read()
except urllib2.URLError,e:
    if hasattr(e,"code"):
        print e.code
    if hasattr(e,"reason"):
        print e.reason
except Exception as e:  #获取所有异常,如果你能明确代码只会有URLError的话 可以不写
    print e

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧