返回信息流http://cuiqingcai.com/993.html 爬百度贴吧的,我是照着敲的,怎么总是匹配不到。。。就是getTitle和getPageNum都get不到。另外为什么每次从网页把代码复制到sublime或者vim里,都有错误,好像所有的中文都出错
# -*- coding:utf-8 -*-
import re, urllib, urllib2
class BDTB:
def __init__(self, baseURL, seeLZ):
self.baseURL = baseURL
self.seeLZ = '?see_lz=' + str(seeLZ)
def getPage(self, pageNum):
try:
url = self.baseURL + self.seeLZ + '&pn=' + str(pageNum)
request = urllib2.Request(url)
response = urllib2.urlopen(request)
with open('haha.txt', 'w') as f:
f.write(response.read())
return response.read()
except urllib2.URLError, e:
if hasattr(e, 'reason'):
print u'连接失败:' , e.reason
return None
def getTitle(self):
page = self.getPage(1)
print type(page)
pattern = re.compile('<h1 class="core_title_txt.*?>(.*?)</h1>',re.S)
result = re.search(pattern,page)
if result:
print result.group(1) #测试输出
return result.group(1).strip()
else:
return None
def getPageNum(self):
page = self.getPage(1)
pattern = re.compile('class="l_reply_num.*?red">(.*?)</span>', re.S)
result = re.search(pattern, page)
if result:
print result.group(1) #测试输出
return result.group(1).strip()
else:
return None# return result.group(1)
baseURL = 'http://tieba.baidu.com/p/3138733512'
bdtb = BDTB(baseURL, 1)
bdtb.getPage(1)
bdtb.getTitle()
bdtb.getPageNum()
这是一条镜像帖。来源:北邮人论坛 / python / #6630同步于 2015/5/3
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
按教程写了个爬虫,失败了……
splendidone
2015/5/3镜像同步8 回复
订阅后,新回复会通过你的通知中心匿名送达。
8 条回复
啊还是解决不了,烦啊,谁来帮下???正则表达式看了两遍了,应该怎么写啊
pattern = re.compile('<a>(.*?)</a>'. re.S)
re.findall(pattern, respinse.read())
这样写匹配字符串能匹配出来,匹配网页就失败,为啥呢
【 在 NotGoodGuy 的大作中提到: 】
: 你试试把抓到的网页打印出来看看,是否跟你用浏览器看到的一样,有可能抓到的网页源代码会有不同,匹配不到。。
果然,,,怎么变成这个样子了?
浏览器返回的源代码有经过渲染、处理之类的吧,自己写的爬虫达不到浏览器所有的功能,所以可能有些内容会有差别,以自己抓到的内容为准。
【 在 splendidone 的大作中提到: 】
: [upload=1][/upload]果然,,,怎么变成这个样子了?