苏飞 发表于 2018-7-21 16:36:13

不懂就问

请问各位大神,
#爬取某一页所有段子信息
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=
    #将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'
呢?
请问应该如何修改?

冬雪雪冬 发表于 2018-7-21 16:49:50

改成:content=content.replace("\n","")

苏飞 发表于 2018-7-21 17:53:40

冬雪雪冬 发表于 2018-7-21 16:49
改成:content=content.replace("\n","")

#提取出用户和内容
    userpat='<h2>(.*?)</h2>'
    #构建段子内容提取的正则表达式
    contentpat='<div class="content">(.*?)(/div)'
谢谢,还想请问一下,为什么H2这个最后要写成<>,而div则是()???
页: [1]
查看完整版本: 不懂就问