|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
请问各位大神,
#爬取某一页所有段子信息
def getcontent(url,page):
#模拟浏览器
headers=('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36')
opener=urllib.request.build_opener()
opener.addheaders=[headers]
#将opener封装为全局
urllib.request.install_opener(opener)
data=urllib.request.urlopen(url).read().decode('utf-8')
#提取出用户和内容
userpat='<h2>(.*?)(/h2)'
#构建段子内容提取的正则表达式
contentpat='<div class="content">(.*?)(/div)'
#x寻找出所有的用户
userlist=re.compile(contentpat,re.S).findall(data)
#寻找出所有的内容
contentlist=re.compile(contentpat,re.S).findall(data)
x=1
#通过for循环遍历段子内容并将内容分别赋给对应的变量
for content in contentlist:
content=content.replace("\n","")
#用字符串作为变量名,先将对应字符串赋给一个变量
name='content'+str(x)
#通过exec()函数实现用字符串作为变量名并赋值
exec(name+'=content')
x+=1
y=1
#通过for循环遍历用户,并输出该用户对应的内容
for user in userlist:
name='content'+str(y)
print('用户'+str(page)+str(y)+'是:'+user)
print('内容是:')
exec('print('+name+')')
print('\n')
y=y+1
#分别获取各页的段子,通过for循环可以获取多页
for i in range(1,30):
url='https://www.qiushibaike.com/8hr/page/'+str(i)
getcontent(url,i)
运行后,为什么总是提醒:Traceback (most recent call last):
File "E:/Pythondemo/糗事百科 翻页爬虫实训四.py", line 41, in <module>
getcontent(url,i)
File "E:/Pythondemo/糗事百科 翻页爬虫实训四.py", line 23, in getcontent
content=content.replace("\n","")
AttributeError: 'tuple' object has no attribute 'replace'
呢?
请问应该如何修改? |
|